Closed Globegitter closed 4 years ago
use the throws route selector:
throws(APIException.apiException(HttpStatusCode.BadRequest) {it: Exception ->
ExceptionDescriptionDTO(it)
}) {
...
}
this will catch and respond the exception, and create the appropriate descriptions.
you can also declare them globally if you use the ktor status pages:
val api = install(OpenAPIGen) { ... }
...
// StatusPage interop, can also define exceptions per-route
install(StatusPages) {
withAPI(api) {
exception<JsonMappingException, Error>(HttpStatusCode.BadRequest) {
it.printStackTrace()
Error("mapping.json", it.localizedMessage)
}
exception<ProperException, Error>(HttpStatusCode.BadRequest) {
it.printStackTrace()
Error(it.id, it.localizedMessage)
}
}
}
Ah cool, thanks for the examples. The first thing that came to my mind and I tried was again using sealed classes so e.g. having
sealed class MyResponses
@Response("An NotFound error response", 404)
data class NotFoundResponse(val message: String): MyResponses()
@Response("Response when request was a success", 201)
object Created: MyResponses()
but this has some drawbacks in itself and what you just posted is more than sufficient for now thanks.
@Request
and @Response
only work on the reified type you declare, subclasses are not analyzed, and at runtime no reflection occurs.
@Wicpar One more question - how can I provide examples for the error responses in the StatusPages
integration?
Another thing I just ran into and I am not sure on how to specify, what if my endpoint has different types it can return and multiple response codes?
Top be precise for that endpoint we return
data class ErrorResponse(val message: String)
in cases where we return a 400, 404 and 500 status but not sure how I can define that.Further when we may return a 201 with en empty response. How can this all be defined? It is not quite clear to me from the existing examples.