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。