Status pages
The StatusPages plugin allows Ktor applications to respond appropriately to any failure state based on a thrown exception or status code.
Add dependencies
To use StatusPages
, you need to include the ktor-server-status-pages
artifact in the build script:
Install StatusPages
To install the StatusPages
plugin to the application, pass it to the install
function in the specified module. The code snippets below show how to install StatusPages
...
... inside the
embeddedServer
function call.... inside the explicitly defined
module
, which is an extension function of theApplication
class.
Configure StatusPages
There are three main configuration options provided by the StatusPages
plugin:
exceptions: configures a response based on mapped exception classes
status: configures a response to a status code value
statusFile: configures a file response from the classpath
Exceptions
The exception
handler allows you to handle calls that result in a Throwable
exception. In the most basic case, the 500
HTTP status code can be configured for any exception:
You can also check specific exceptions and respond with the required content:
Status
The status
handler provides the capability to respond with specific content based on the status code. The example below shows how to respond on requests if the resource is missing on a server (the 404
status code):
Status file
The statusFile
handler allows you to serve HTML pages based on the status code. Suppose your project contains the error401.html
and error402.html
HTML pages in the resources
folder. In this case, you can handle the 401
and 402
status codes using statusFile
as follows:
The statusFile
handler replaces any #
character with the value of the status code within the list of configured statuses.