Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท Plugins and Serialization

Status Pages and Error Handling

Handle errors cleanly in Ktor with the StatusPages plugin: map exceptions to JSON error responses, custom exception classes, status handlers for 404, and safe 500s.

Things go wrong in every server: a client sends garbage, a record does not exist, a database is down, a bug throws a NullPointerException. Without a plan each of these becomes a stack trace, an empty 500, or worse, a leaked internal message. The StatusPages plugin gives you one place to decide how every error looks. This lesson sets it up, builds an error hierarchy for your domain, and includes a runnable stand-in that reproduces how Ktor chooses a handler for an exception.

Installing StatusPages

Dependency: ktor-server-status-pages.

Kotlin
import io.ktor.server.plugins.statuspages.*

@Serializable
data class ErrorBody(val error: String, val message: String? = null)

fun Application.module() {
    install(ContentNegotiation) { json() }
    install(StatusPages) {
        exception<IllegalArgumentException> { call, cause ->
            call.respond(HttpStatusCode.BadRequest, ErrorBody("bad_request", cause.message))
        }
        exception<NotFoundException> { call, cause ->
            call.respond(HttpStatusCode.NotFound, ErrorBody("not_found", cause.message))
        }
        exception<Throwable> { call, cause ->
            call.application.log.error("Unhandled error on ${call.request.uri}", cause)
            call.respond(HttpStatusCode.InternalServerError, ErrorBody("internal_error"))
        }
        status(HttpStatusCode.NotFound) { call, status ->
            call.respond(status, ErrorBody("not_found", "No route for ${call.request.path()}"))
        }
    }
    routing { /* ... */ }
}

There are two kinds of handler:

  • exception<T> { call, cause -> ... } runs when a handler (or plugin) throws T or a subclass.
  • status(code) { call, status -> ... } runs when a response with that status was produced without a body, for example the automatic 404 when no route matches.

The most specific exception class wins, so a handler for NotFoundException beats the catch-all for Throwable. Always keep a Throwable handler: it guarantees clients get a consistent body, and it is the right place to log the full stack trace while showing the client nothing sensitive.

Never put cause.message of an unexpected exception into a response. Messages from the database or file system can reveal table names, paths or SQL. Return a generic message plus an ID, and log the details on the server.

A domain exception hierarchy

Instead of sprinkling call.respond(HttpStatusCode.NotFound, ...) through handlers, throw meaningful exceptions from your services and let StatusPages translate them once:

Kotlin
sealed class AppException(message: String, val status: HttpStatusCode) : RuntimeException(message)
class NotFound(what: String) : AppException("$what not found", HttpStatusCode.NotFound)
class Conflict(message: String) : AppException(message, HttpStatusCode.Conflict)
class Forbidden(message: String = "Not allowed") : AppException(message, HttpStatusCode.Forbidden)
class ValidationFailed(val problems: List<String>) :
    AppException("Validation failed", HttpStatusCode.UnprocessableEntity)

install(StatusPages) {
    exception<AppException> { call, e ->
        call.respond(e.status, ErrorBody(e.status.description.lowercase().replace(' ', '_'), e.message))
    }
    exception<Throwable> { call, e ->
        call.application.log.error("Unhandled", e)
        call.respond(HttpStatusCode.InternalServerError, ErrorBody("internal_error"))
    }
}

get("/books/{id}") {
    val book = repo.find(call.parameters.getOrFail<Int>("id")) ?: throw NotFound("Book")
    call.respond(book)
}

The route reads like the happy path; the error format lives in one place. Ktor's own exceptions fit in too: BadRequestException (400), NotFoundException (404), MissingRequestParameterException, ParameterConversionException and ContentTransformationException (all 400). With a Throwable catch-all they would become 500s unless you map them, so add a handler for BadRequestException.

A consistent error format

Pick one JSON shape for every error and keep it. A good minimal shape is { "error": "code", "message": "human text" }, optionally with details for validation problems. The standard "Problem Details" format (RFC 9457, application/problem+json) is another good choice. Clients can then handle errors in one place.

Stand-in: finding the most specific handler

Ktor picks, among registered exception handlers, the one for the closest superclass of the thrown exception. This stand-in replicates that by walking the Java class chain from the thrown exception up to Throwable. A set of actions throws various exceptions, and the "StatusPages" object turns each into a status and a JSON body.

Kotlin Stand-in: exception to response mapping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Check: NotFound has its own handler, Conflict falls back to the AppException handler (its superclass), NumberFormatException is handled specifically even though it is an IllegalArgumentException, and a NullPointerException from the "bug" lands in the Throwable catch-all, returning a safe 500.

status handlers and empty responses

A status(HttpStatusCode.NotFound) handler runs for responses that have that status and no body, such as the automatic 404. You can use it to return the same JSON error body for unknown URLs. Do not use it to rewrite responses your handlers deliberately produced with their own bodies.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Two handlers exist: exception<AppException> and exception<Throwable>. A Conflict (subclass of AppException) is thrown. Which runs?

    The most specific matching superclass handler is selected.
  2. 2. Why log the exception in the Throwable handler but return a generic body?

    Internal messages can leak sensitive details, so log them server side only.
  3. 3. What triggers a status(HttpStatusCode.NotFound) { ... } handler?

    Status handlers react to bodiless responses with that status code.
  4. 4. What is a benefit of throwing domain exceptions such as NotFound from services?

    StatusPages translates the exceptions centrally.

Summary

  • StatusPages turns exceptions and bodiless status codes into consistent responses.
  • The most specific exception<T> handler wins; always include a Throwable catch-all that logs and returns a safe 500.
  • Define domain exceptions with an HTTP status and translate them in one handler.
  • Use one error format across the API; never leak internal messages.

Next: Request Validation