When using the `ContentNegotiation` feature with J...
# ktor
d
When using the
ContentNegotiation
feature with Jackson for JSON bodies Ktor responds with HTTP 500 if the client sends invalid JSON or JSON that does not match the data classes I am trying to receive. I would expect HTTP 400 instead. Is there a way to configure this?
s
haven't used it but it seems it can customize the behavior: https://ktor.io/servers/features/status-pages.html
👍 1
d
Copy code
install(StatusPages) {
        exception<JsonProcessingException> {
            call.respond(HttpStatusCode.BadRequest, "Invalid JSON")
        }
    }
Solved it for me. Strange that this isn't the default for Jackson serialization.
m
Not sure how it could be the default. What response do you want to send? Plain text? JSON? Stack trace or not?
d
Anything else would be better than just HTTP 500 + empty body. I'd expect HTTP 400 + empty body for bad requests by default. Not a response that indicates "the server is broken".
m
500 doesn't indicate the server is broken. It indicates an internal error, which is what happened.
d
It indicates an internal server error, yes. Which means the client is not at fault.
m
No, it means that an error occurred and it wasn't successfully detected as invalid input. There are plenty of other cases where such a thing could happen, as well. Suppose you send a negative number instead of a positive one. It will deserialize just fine still, but perhaps some internal logic won't know how to handle that. Boom, 500. Doesn't mean it wasn't invalid input.
In a perfect world, sure, 500 would always mean that the input was 100% valid (otherwise it would have been a 4xx). But, that's not the world we inhabit 😕
d
re negative numbers: That's an entirely different thing, because then yes, my application is at fault. But I'd expect a JSON deserializer in a web framework to handle invalid input and not just throw exceptions which then propagate as http 500 to the client. Spring doesn't do that either 😉