https://kotlinlang.org logo
#ktor
Title
# ktor
r

ribesg

07/01/2021, 10:21 AM
What’s your strategy to return meaningful error to the user from a Ktor Server when using Kotlinx Serialization to parse the body of a request, and the body isn’t valid?
h

hfhbd

07/01/2021, 10:27 AM
Personally, I don't use
ktor-serialization
but instead custom shortcuts to handle serialization. When failing I return
400 BadRequest
.
r

ribesg

07/01/2021, 10:43 AM
I’m trying to find a good way to to return clear messages with the 400 response. Like, this field is missing or has an invalid value/type, this kind of things. For now the only way I found was to make a “safer” version of each model, with all fields nullable and then check everything myself…
h

hfhbd

07/01/2021, 10:45 AM
You could simple return the json exception message
h

Hasan Hosgel (alosdev)

07/01/2021, 11:19 AM
I created a save retrieve, which catches the json exception and propagates a bad request exception
t

thanksforallthefish

07/01/2021, 11:32 AM
I am not using ktor, but basically we had the same problem. and it turned out the easier way (for us) was to use nullable fields in the representation and do validation on them. frameworks like hibernate-validator creates awesome violation description, from which you can extract the exact path of the failure and the description of it. alternatively, https://github.com/valiktor/valiktor can probably help you as well and being more kotlin-esque
but never used valiktor, I am quite happy with hibernate validator and given the popularity it is quite easy to find docs and examples online
r

ribesg

07/01/2021, 12:37 PM
Thanks. I don’t see a better solution than returning the serializer error message, even if it isn’t great. It can work for this specific API as it isn’t public, but not really a great solution
c

christophsturm

07/02/2021, 7:57 AM
you could also validate the request with json schema
r

ribesg

07/02/2021, 12:38 PM
I don’t want to have more than one source of truth about what the model looks like, especially in a single project. I’m more into defining the model as a KMP lib that can be used both in the backend and frontend, so defining it twice in a single project is a no-no
c

christophsturm

07/02/2021, 12:46 PM
the question is what you consider meaningful error messages. if its only about nullability, data types and mandatory fields, i think it should be done in kotlinx.serialization.
6 Views