Has anyone had success using `kotlinx-serializatio...
# server
n
Has anyone had success using
kotlinx-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:
Copy code
{
  "code": "400",
  "name": "Bad Request",
  "description": "field 'name' cannot be null"
}
I end up having to do something like
Copy code
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.
c
I don't use Spring, but I do use Ktor, hopefully that gives you a path forward; With Ktor, what you'd do is use the
ErrorPages
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.
d
In Spring there's
@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.