回應驗證
預設情況下,Ktor 不會根據其狀態碼驗證 回應。 如果需要,您可以使用以下驗證策略:
- 使用
expectSuccess
屬性來針對非 2xx 回應拋出例外狀況。 - 新增更嚴格的 2xx 回應驗證。
- 自訂非 2xx 回應的驗證。
啟用預設驗證
Ktor 允許您透過將 expectSuccess
屬性設定為 true
來啟用預設驗證。 這可以在 用戶端配置 層級上完成...
kotlin
import io.ktor.client.*
import io.ktor.client.engine.cio.*
val client = HttpClient(CIO) {
expectSuccess = true
}
... 或透過在 請求 層級使用相同的屬性。 在此情況下,將會針對非 2xx 錯誤回應拋出以下例外狀況:
- RedirectResponseException 針對 3xx 回應。
- ClientRequestException 針對 4xx 回應。
- ServerResponseException 針對 5xx 回應。
自訂驗證
您可以為 2xx 回應新增額外驗證,或透過使用 HttpCallValidator 插件(plugin)來自訂預設驗證。若要安裝 HttpCallValidator
,請在 用戶端配置區塊 內呼叫 HttpResponseValidator 函數:
kotlin
val client = HttpClient(CIO) {
HttpResponseValidator {
// ...
}
}
驗證 2xx 回應
如上所述,預設驗證 會針對非 2xx 錯誤回應拋出例外狀況。如果您需要新增 更嚴格的驗證並檢查 2xx 回應,請使用 HttpCallValidator
中可用的 validateResponse 函數。
在下面的 範例 中,用戶端收到一個包含錯誤詳細資訊的 2xx 回應,其格式為 JSON。 validateResponse
用於引發 CustomResponseException
:
kotlin
val client = HttpClient(CIO) {
install(ContentNegotiation) { json() }
HttpResponseValidator {
validateResponse { response ->
val error: Error = response.body()
if (error.code != 0) {
throw CustomResponseException(response, "Code: ${error.code}, message: ${error.message}")
}
}
}
}
處理非 2xx 例外狀況
如果您需要自訂 預設驗證 並以特定方式處理非 2xx 回應的例外狀況, 請使用 handleResponseExceptionWithRequest。 在下面的 範例 中,用戶端針對 404 回應引發自訂的 MissingPageException
而不是預設的 ClientRequestException
:
kotlin
val client = HttpClient(CIO) {
expectSuccess = true
HttpResponseValidator {
handleResponseExceptionWithRequest { exception, request ->
val clientException = exception as? ClientRequestException ?: return@handleResponseExceptionWithRequest
val exceptionResponse = clientException.response
if (exceptionResponse.status == HttpStatusCode.NotFound) {
val exceptionResponseText = exceptionResponse.bodyAsText()
throw MissingPageException(exceptionResponse, exceptionResponseText)
}
}
}
}