Server Plugin
状态页
必需的依赖项: io.ktor:ktor-server-status-pages
代码示例: status-pages
原生服务器支持: ✅ Ktor 支持 Kotlin/Native,并且允许你在没有额外运行时或虚拟机的情况下运行服务器。
StatusPages 插件允许 Ktor 应用程序根据抛出的异常或状态码对任何失败状态做出适当的响应。
添加依赖项
要使用 StatusPages,你需要在构建脚本中引入 ktor-server-status-pages artifact:
Kotlin
Groovy
XML
安装 StatusPages
要将 StatusPages 插件安装到应用程序中,请在指定的
模块
中将其传递给 模块允许你通过对路由进行分组来组织你的应用程序。
install 函数。 下面的代码片段展示了如何安装 StatusPages …… - ……在
embeddedServer函数调用内部。 - ……在显式定义的
module内部,该module是Application类的扩展函数。
kotlin
kotlin
配置 StatusPages
StatusPages 插件提供了三个主要的配置选项:
异常
exception 处理程序允许你处理导致 Throwable 异常的调用。在最基本的情况下,可以为任何异常配置 500 HTTP 状态码:
kotlin
install(StatusPages) {
exception<Throwable> { call, cause ->
call.respondText(text = "500: $cause" , status = HttpStatusCode.InternalServerError)
}
}你也可以检测特定异常并用所需内容进行响应:
kotlin
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)
}
}
}状态
status 处理程序提供了根据状态码响应特定内容的能力。下面的示例展示了当服务器上缺少资源(404 状态码)时如何响应请求:
kotlin
install(StatusPages) {
status(HttpStatusCode.NotFound) { call, status ->
call.respondText(text = "404: Page Not Found", status = status)
}
}状态文件
statusFile 处理程序允许你根据状态码提供 HTML 页面。假设你的项目在 resources 文件夹中包含 error401.html 和 error402.html HTML 页面。在这种情况下,你可以按如下方式使用 statusFile 处理 401 和 402 状态码:
kotlin
install(StatusPages) {
statusFile(HttpStatusCode.Unauthorized, HttpStatusCode.PaymentRequired, filePattern = "error#.html")
}statusFile 处理程序会将配置状态列表中的任何 # 字符替换为状态码的值。
你可以在此处找到完整示例:status-pages。
