StatusPages feature allows Ktor applications to respond appropriately to any failure state. This feature is installed using the standard application configuration:
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
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.
More specific responses can allow for more complex user interactions.
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.
Single handling also implies that recursive call stacks are avoided. For example, this configuration would result in the created
IllegalStateException propagating to the client.
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:
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.
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.
This will resolve two resources from the classpath.
On a 404, it will return error404.html.
On a 401, it will return error401.html.
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.
Other frameworks, use exceptions on redirect, so the normal flow is broken and you can execute redirections in guard clauses or subfunctions without having to worry about returning in all the subfunction chain. You can use the StatusPages feature to simulate this: