Response Validation

Estimated reading time: 1 minute

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

This feature is defined in the class io.ktor.client.features.HttpCallValidator and no additional artifacts are required.

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
}