Code examples: client-validate-2xx-response, client-validate-non-2xx-response
Ktor allows you to validate a response depending on its status code.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.
Ktor allows you to enable default validation by setting the expectSuccess
property to true
.
This can be done on a client configuration level ...
{src="snippets/_misc_client/BasicClientConfig.kt"}
... 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.
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 {
// ...
}
}
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
:
{src="snippets/client-validate-2xx-response/src/main/kotlin/com/example/Application.kt" lines="23-33"}
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
:
{src="snippets/client-validate-non-2xx-response/src/main/kotlin/com/example/Application.kt" lines="18-30"}