Skip to main content

Status Pages in Ktor

·2 mins

The StatusPages plugin in Ktor is a powerful tool for handling error responses and exceptions in a structured and user-friendly way. By defining how different types of failures are managed, it improves the user experience by providing clear, consistent feedback when something goes wrong.

Example: Installing StatusPages #

In the following example, the StatusPages plugin is installed to handle Http 404 (Not Found) errors and general exceptions.

install(StatusPages) {
    status(HttpStatusCode.NotFound) { call, cause ->
        call.respond(
            status = HttpStatusCode.NotFound,
            message = mapOf("error" to "Resource not found")
        )
    }
    exception<Throwable> { call, cause ->
        call.respondText(
            text = "500: $cause", 
            status = HttpStatusCode.InternalServerError
        )
    }
}

Handling 404 Errors #

If you navigate to a URL that hasn’t been routed, the server will return a 404 response with the following JSON as the response body:

{
    "error": "Resource not found"
}

You can use call or cause to provide additional details in the response if needed.

Handling General Exceptions #

Similarly, any unhandled exceptions thrown while processing a request will trigger the exception block. Within this block, you can use the cause: Throwable parameter to determine the type of exception and tailor the response accordingly.

exception<Throwable> { call, cause ->
    call.respondText(
        text = "500: $cause", 
        status = HttpStatusCode.InternalServerError
    )
}

Custom Exception Handling #

For more specific error handling, you can check the type of exception and return a corresponding response. For example, if your application throws an AuthorizationException, you can return an HTTP 403 (Forbidden) response:

install(StatusPages) {
    exception<Throwable> { call, cause ->
        if (cause is AuthorizationException) {
            call.respondText(
                text = "403: $cause", 
                status = HttpStatusCode.Forbidden
            )
        } else {
            call.respondText(
                text = "500: $cause",
                status = HttpStatusCode.InternalServerError
            )
        }
    }
}

Why Use StatusPages? #

The StatusPages plugin adds structure and consistency to error handling in your Ktor application. Instead of spread around error responses across your routes, you can centralize them, making your codebase cleaner and more maintainable. With StatusPages, you can create meaningful, user-friendly error messages while gracefully managing various failure scenarios.