What’s your strategy to return meaningful error to...
# ktor
r
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
Personally, I don't use
ktor-serialization
but instead custom shortcuts to handle serialization. When failing I return
400 BadRequest
.
r
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
You could simple return the json exception message
h
I created a save retrieve, which catches the json exception and propagates a bad request exception
t
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
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
you could also validate the request with json schema
r
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
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.