Nick
12/11/2024, 5:54 PMkotlinx-serialization
in a Spring app? I haven't found an easy way to return nice, formatted HTTP responses when serialization fails for some reason.
For example, a user sends a request, making a String field null when it should not be null.
Since it should not be null, I want to model it in my domain as a non-nullable String, but if I do, kotlinx-serialization will throw a a serialization exception which is difficult to handle in a way that can programmatically discern the reason why serialization failed and send that back in a user-friendly response.
• Example:
{
"code": "400",
"name": "Bad Request",
"description": "field 'name' cannot be null"
}
I end up having to do something like
data class User(name: String? = null)
and then validate that it's not null after serialization
Wish there was a way to intercept the request before serialization, and check for any null values that should not be null, and return a nice, user-readable error in response.CLOVIS
12/11/2024, 10:37 PMErrorPages
plugin to decide what is displayed when an error is thrown. There, you get the serialization error thrown by KotlinX.Serialization, and you can decide to return another object instead, which you can format in however way you want.David Kubecka
12/13/2024, 8:38 AM@ControllerAdvice
for this. I recommend looking at ResponseEntityExceptionHandler
for how the common errors are handled and potentially extending it.
For instance, I translate HttpMessageNotReadableException
and its cause MissingKotlinParameterException
to a custom "FIELD_MISSING" error.kqr
12/13/2024, 12:02 PM