Response validation
By default, Ktor doesn't validate a response depending on its status code. If required, you can use the following validation strategies:
Use the
expectSuccess
property to throw exceptions for non-2xx responses.Add stricter validation of 2xx responses.
Customize validation of non-2xx responses.
Enable default validation
Ktor allows you to enable default validation by setting the expectSuccess
property to true
. This can be done on a client configuration level ...
... or by using the same property on a request level. In this case, the following exceptions will be thrown for non-2xx error responses:
RedirectResponseException for 3xx responses.
ClientRequestException for 4xx responses.
ServerResponseException for 5xx responses.
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 handleResponseExceptionWithRequest. In the example below, a client raises a custom MissingPageException
for 404 responses instead of the default ClientRequestException
: