'How do I handle Request Body Error in Ktor

I am new to Ktor and I have a route with a request body which i am parsing with Kotlin Serialization.

I know that the request body is expected to conform to the request body data class but then, I tested by passing the wrong field in my test payload and it crashed the app.

I want to be able to handle such scenarios and respond to the client that such a field is not allowed. How do i go about that.

This is my sample data class:

@kotlinx.serialization.Serializable
data class UserLoginDetails(
    var email: String = "",
    var password: String = ""
)

This is the route:

post("/user/login") {
   val userInfo  = call.receive<UserLoginDetails>()
   //my code here
}

The payload below works

{
   "email": "[email protected]",
   "password": "password"
}

But if use an alternative payload for instance:

{
    "phone": "[email protected]",
    "password": "password"
}

The app crashes with the crash message:

kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 7: Encountered an unknown key 'emai'. Use 'ignoreUnknownKeys = true' in 'Json {}' builder to ignore unknown keys.



Solution 1:[1]

You have two options in Ktor:

  1. call.receive is the function which can throw an exception in this case, you can simply catch it:
try {
    val userInfo = call.receive<UserLoginDetails>()
} catch (t: Throwable) {
    // handle error
}
  1. Catching exceptions globally using Status Pages:
install(StatusPages) {
    exception<SerializationException> { cause ->
        call.respond(/* */)
    }
}

Solution 2:[2]

The error message says you can setup your Json with the config ignoreUnknownKeys = true where you are creating the Json object. Here's the doc link.

a tip: You might also want to check other configuration options so you can avoid setting empty string as default values.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pylyp Dukhov
Solution 2 Rahul Sainani