Hi, I have been trying to handle 415 Unsupported m...
# ktor
p
Hi, I have been trying to handle 415 Unsupported media type request in ktor server http POST https://baseurl/api/v1/register (the request i am sending is particularly missing some form params like email) and it responds with - Cannot transform this request's content to com.example.app.data.RegisterRequest while i want to send a custom response Is there something i am missing here or do i need to use some anti patterns like make params nullable and check that once deserialized? I tried handling with status page but doesn't seem to work
Copy code
install(StatusPages) {
            exception<Exception> { call, _ ->
                call.respond(HttpStatusCode.BadRequest, "Invalid request format")
                logger.error("Unhandled exception occurred")
            }
            this.unhandled {
                logger.error("Unhandled exception occurred", it)
            }
        }

        install(StatusPages) {
            exception<ContentTransformationException> { call, _ ->
                call.respond(HttpStatusCode.BadRequest, "Invalid request format")
            }
            exception<io.ktor.server.plugins.ContentTransformationException> { call, _ ->
                call.respond(HttpStatusCode.BadRequest, "Invalid request format")
            }
        }
a
Can you please share the code for the
/api/v1/register
route handler and the request that leads to the error, preferably as a curl command?
p
This is normal request with expected result
Copy code
curl --request POST \
  --url <https://example.com/api/v1/register> \
  --header 'content-type: application/json' \
  --data '{
  "username": "username",
  "email": "<mailto:email@example.com|email@example.com>",
  "password": "password"
}'
while this one fails
Copy code
curl --request POST \
  --url <https://example.com/api/v1/register> \
  --header 'content-type: application/json'
415 Unsupported Media Type Cannot transform this request's content to com.app.SetupRequest.Register
a
Can you please share the definition of the
com.app.SetupRequest.Register
and the serialization configuration?
p
Copy code
@Serializable
data class Register(val username: String, val email: String, val password: String)
thats simply a data class with kotlinx serialization and post request is created as
Copy code
post<SetupRoute.Register, SetupRequest.Register> { _, registerData ->
    val response = setupResource.handleRegistration(registerData = registerData)
    call.respond(apiResponse = response)
}
request does not even reach inside post block
a
That's because if you use the default JSON format, it's required that the JSON object be present in the request and contain all the fields of the
Register
class.
p
oh, got it, thanks for pointing that out. I completely missed that