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

diesieben07

03/31/2020, 3:13 PM
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

SerVB

03/31/2020, 3:27 PM
haven't used it but it seems it can customize the behavior: https://ktor.io/servers/features/status-pages.html
👍 1
d

diesieben07

03/31/2020, 3:30 PM
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

mp

03/31/2020, 3:44 PM
Not sure how it could be the default. What response do you want to send? Plain text? JSON? Stack trace or not?
d

diesieben07

03/31/2020, 3:46 PM
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

mp

03/31/2020, 3:46 PM
500 doesn't indicate the server is broken. It indicates an internal error, which is what happened.
d

diesieben07

03/31/2020, 3:46 PM
It indicates an internal server error, yes. Which means the client is not at fault.
m

mp

03/31/2020, 3:48 PM
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

diesieben07

03/31/2020, 3:53 PM
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 😉
7 Views