Response Validation

预计阅读时间: 2 分钟

This feature allows to validate HTTP response and handle transformation exceptions from engine and pipelines.

本特性在 io.ktor.client.features.HttpCallValidator 类中定义,无需任何额外构件。

Configuration

To configure response validation feature use validateResponse and handleResponseException methods:

HttpResponseValidator {
    validateResponse { response: HttpResponse ->
        // ...
    }

    handleResponseException { cause: Throwable ->
        // ...
    }
}

This feature could be configured multiple times; all validators and handlers are saved and called in order of install.

Expect success

The ExpectSuccess feature implemented using response validation:

HttpResponseValidator {
    validateResponse { response ->
        val statusCode = response.status.value
        when (statusCode) {
            in 300..399 -> throw RedirectResponseException(response)
            in 400..499 -> throw ClientRequestException(response)
            in 500..599 -> throw ServerResponseException(response)
        }

        if (statusCode >= 600) {
            throw ResponseException(response)
        }
    }
}

The feature is installed by default, but could be disabled in the client configuration:

val client = HttpClient() {
    expectSuccess = false
}