Skip to content

响应验证

默认情况下,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 错误响应,将抛出以下异常:

自定义验证

您可以通过使用 HttpCallValidator 插件来为 2xx 响应添加额外的验证或自定义默认验证。要安装 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)
            }
        }
    }
}