Is it possible to set RetryPolicy in spring-retry based on HttpStatus status code?

Marat Kurbanov picture Marat Kurbanov · Dec 1, 2014 · Viewed 9.5k times · Source

Is it possible to set RetryPolicy in spring retry (https://github.com/spring-projects/spring-retry) based on error status code? e.g. I want to retry on HttpServerErrorException with HttpStatus.INTERNAL_SERVER_ERROR status code, which is 503. Therefore it should ignore all other error codes -- [500 - 502] and [504 - 511].

Answer

Artem Bilan picture Artem Bilan · Dec 2, 2014

The RestTemplate has setErrorHandler option and DefaultResponseErrorHandler is the default one.

Its code looks like:

public void handleError(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = getHttpStatusCode(response);
    switch (statusCode.series()) {
        case CLIENT_ERROR:
            throw new HttpClientErrorException(statusCode, response.getStatusText(),
                    response.getHeaders(), getResponseBody(response), getCharset(response));
        case SERVER_ERROR:
            throw new HttpServerErrorException(statusCode, response.getStatusText(),
                    response.getHeaders(), getResponseBody(response), getCharset(response));
        default:
            throw new RestClientException("Unknown status code [" + statusCode + "]");
    }
}

So, you can provide your own implementation for that method to simplify your RetryPolicy around desired status codes.