What is best approach to handle exception for vari...
# ktor
n
What is best approach to handle exception for various accept content types? For example, if client asks
application/json
, I would like serialize exception using gson. If client asks
text/html
, then simple html page and for
text/plain
print only message.
g
check ContentNegotiation Ktor feature
c
Something like that
Copy code
install(ContentNegotiation) {
    gson {
        setPrettyPrinting()
    }
}
install(StatusPages) {
    exception<FileNotFoundException> { t ->
        call.respond(...)
    }
}
n
I have same solution. Problem is, I am needed different serialisers for normal response and errors
For example, my code is:
Copy code
install(ContentNegotiation) {
        val converter = JacksonConverter(objectMapper)
        register(ContentType.Application.Json, converter)
    }
    install(StatusPages) {
        exception<BackendException> { cause ->
            call.respond(cause.responseStatus, cause.errorResponse)
        }
        exception<ValidationException> { cause ->
            call.respond(HttpStatusCode.InternalServerError, ErrorResponse(OTHER, message = cause.localizedMessage))
        }
    }
So, I want convert all
ErrorResponse()
to various content types. But for
OK
responses I would like support only
application/json
. It looks like separate
ContentNegotiation
for
StatusPages
. Is there any pattern to accomplish this?