Handle Exceptions and Customize Status Pages

The StatusPages feature allows Ktor applications to respond appropriately to any failure state. This feature is installed using the standard application configuration:

  1. fun Application.main() {
  2. install(StatusPages)
  3. }

There are three main configuration options provided to StatusPages:

  • exceptions - Configures response based on mapped exception classes
  • status - Configures response to status code value
  • statusFile - Configures standard file response from classpath

    This feature is defined in the class io.ktor.features.StatusPages and no additional artifacts are required.

Table of contents:

Exceptions

The exception configuration can provide simple interception patterns for calls that result in a thrown exception. In the most basic case, a 500 HTTP status code can be configured for any exceptions.

  1. install(StatusPages) {
  2. exception<Throwable> { cause ->
  3. call.respond(HttpStatusCode.InternalServerError)
  4. }
  5. }

More specific responses can allow for more complex user interactions.

  1. install(StatusPages) {
  2. exception<AuthenticationException> { cause ->
  3. call.respond(HttpStatusCode.Unauthorized)
  4. }
  5. exception<AuthorizationException> { cause ->
  6. call.respond(HttpStatusCode.Forbidden)
  7. }
  8. }

These customizations can work well when paired with custom status code responses, e.g. providing a login page when a user has not authenticated.

Each call is only caught by a single exception handler, the closest exception on the object graph from the thrown exception. When multiple exceptions within the same object hierarchy are handled, only a single one will be executed.

  1. install(StatusPages) {
  2. exception<IllegalStateException> { cause ->
  3. fail("will not reach here")
  4. }
  5. exception<ClosedFileSystemException> {
  6. throw IllegalStateException()
  7. }
  8. }
  9. intercept(ApplicationCallPipeline.Fallback) {
  10. throw ClosedFileSystemException()
  11. }

Single handling also implies that recursive call stacks are avoided. For example, this configuration would result in the created IllegalStateException propagating to the client.

  1. install(StatusPages) {
  2. exception<IllegalStateException> { cause ->
  3. throw IllegalStateException("")
  4. }
  5. }

Logging Exceptions

It is important to note that adding the handlers above will “swallow” the exceptions generated by your routes. In order to log the actual errors generated, you can either log the cause manually, or simply re-throw it as shown below:

  1. install(StatusPages) {
  2. exception<Throwable> { cause ->
  3. call.respond(HttpStatusCode.InternalServerError, "Internal Server Error")
  4. throw cause
  5. }
  6. }

Status

The status configuration provides a custom actions for status responses from within the application. Below is a basic configuration that provides information about the HTTP status code within the response text.

  1. install(StatusPages) {
  2. status(HttpStatusCode.NotFound) {
  3. call.respond(TextContent("${it.value} ${it.description}", ContentType.Text.Plain.withCharset(Charsets.UTF_8), it))
  4. }
  5. }

StatusFile

While the status configuration provides customizable actions on the response object, the more common solution is to provide an error HTML page that visitors will see on an error or authorization failure. The statusFile configuration provides that type of functionality.

  1. install(StatusPages) {
  2. statusFile(HttpStatusCode.NotFound, HttpStatusCode.Unauthorized, filePattern = "error#.html")
  3. }

This will resolve two resources from the classpath.

  • On a 404, it will return error404.html.
  • On a 401, it will return error401.html.The statusFile configuration replaces any # character with the value of the status code within the list of configured statuses.

Redirections using StatusPages

When doing redirections by executing call.respondRedirect("/moved/here", permanent = true), the rest of the callee function is executed.So when doing redirections inside guard clauses, you have to return the function.

  1. routing {
  2. get("/") {
  3. if (condition) {
  4. return@get call.respondRedirect("/invalid", permanent = false)
  5. }
  6. call.respondText("Normal response")
  7. }
  8. }

Other frameworks, use exceptions on redirect, so the normal flow is broken and you can execute redirections in guardclauses or subfunctions without having to worry about returning in all the subfunction chain. You can use the StatusPagesfeature to simulate this:

  1. fun Application.module() {
  2. install(StatusPages) {
  3. exception<HttpRedirectException> { e ->
  4. call.respondRedirect(e.location, permanent = e.permanent)
  5. }
  6. }
  7. routing {
  8. get("/") {
  9. if (condition) {
  10. redirect("/invalid", permanent = false)
  11. }
  12. call.respondText("Normal response")
  13. }
  14. }
  15. }
  16. class HttpRedirectException(val location: String, val permanent: Boolean = false) : RuntimeException()
  17. fun redirect(location: String, permanent: Boolean = false): Nothing = throw HttpRedirectException(location, permanent)

There is a more advanced example showing this in the redirect-with-exception sample.