Ktor 1.6.4 Help

Response validation

The Ktor client includes validation of non-2xx responses by default. For example, the client throws ClientRequestException for 4xx error responses. If required, you can add additional validation for 2xx responses or customize default validation by using HttpCallValidator.

Default validation

By default, the Ktor client throws exceptions for non-2xx error responses:

You can add additional validation for 2xx responses by using the validateResponse function available in HttpCallValidator. If you need to customize handling of non-2xx exceptions, you can use handleResponseException.

Default validation is controlled by the expectSuccess property. If necessary, you can disable it on a client configuration level using the expectSuccess property ...

import io.ktor.client.* import io.ktor.client.engine.cio.* val client = HttpClient(CIO) { expectSuccess = false }

... or by using the same property on a request level.

Custom validation

You can add additional validation for 2xx responses or customize default validation by using the HttpCallValidator plugin. To install HttpCallValidator, call the HttpResponseValidator function inside a client configuration block:

val client = HttpClient(CIO) { HttpResponseValidator { // ... } }

Validate 2xx responses

As mentioned above, default validation throws exceptions for non-2xx error responses. If you need to add stricter validation and check 2xx responses, use the validateResponse function available in HttpCallValidator.

In the example below, a client receives a 2xx response with error details in a JSON format. The validateResponse is used to raise a CustomResponseException:

val client = HttpClient(CIO) { install(JsonFeature) HttpResponseValidator { validateResponse { response -> val error = response.receive<Error>() if (error.code != 0) { throw CustomResponseException(response, "Code: ${error.code}, message: ${error.message}") } } } }

Handle non-2xx exceptions

If you need to customize default validation and handle exceptions for non-2xx responses in a specific way, use handleResponseException. In the example below, a client raises a custom MissingPageException for 404 responses instead of the default ClientRequestException:

val client = HttpClient(CIO) { HttpResponseValidator { handleResponseException { exception -> val clientException = exception as? ClientRequestException ?: return@handleResponseException val exceptionResponse = exception.response if (exceptionResponse.status == HttpStatusCode.NotFound) { val exceptionResponseText = exceptionResponse.readText() throw MissingPageException(exceptionResponse, exceptionResponseText) } } } }
Last modified: 30 June 2021