Server Plugin
狀態頁面
必要相依性:io.ktor:ktor-server-status-pages
程式碼範例: status-pages
原生伺服器 支援:✅ Ktor 支援 Kotlin/Native,並允許您在沒有額外執行階段或虛擬機的情況下執行伺服器。
StatusPages 外掛程式允許 Ktor 應用程式根據拋出的例外或狀態碼,對任何失敗狀態做出適當的回應。
新增相依性
若要使用 StatusPages,您需要在組建指令碼中包含 ktor-server-status-pages 構件:
Kotlin
Groovy
XML
安裝 StatusPages
若要將 StatusPages 外掛程式安裝到應用程式,請將其傳遞給指定
模組
中的 模組允許您透過分組路由來組織您的應用程式。
install 函式。 以下程式碼片段顯示如何安裝 StatusPages ... - ... 在
embeddedServer函式呼叫內。 - ... 在明確定義的
module內,該模組是Application類別的擴充函式。
kotlin
kotlin
配置 StatusPages
StatusPages 外掛程式提供了三個主要的配置選項:
- exceptions:根據對應的例外類別配置回應
- status:針對狀態碼值配置回應
- statusFile:從類別路徑配置檔案回應
例外
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。
