3

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": "test@email.com",
   "password": "password"
}

But if use an alternative payload for instance:

{
    "phone": "test@email.com",
    "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.

Joseph Ofem
  • 304
  • 2
  • 15

2 Answers2

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(/* */)
    }
}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
0

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.

Rahul Sainani
  • 3,437
  • 1
  • 34
  • 48