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:
RedirectResponseException for 3xx responses.
ClientRequestException for 4xx responses.
ServerResponseException for 5xx 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 ...
... 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:
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
:
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
: