How do I perform retry based on HTTP response code in Springboot

2.9k views Asked by At
@Retryable(value = ABCDException.class,
        maxAttemptsExpression = 3,
        backoff = @Backoff(delayExpression = "#{${application.delay}}"))

public String postABCDrequest(ABCDrequest abcdRequest) throws ABCDException {
    try {
        return restCalltopostData(abcdRequest);
    } catch (AnyException e) {
        log.error("Error Occured ", e);
        throw new ABCDException("Error Occured ", e);
    }
}

In this method, I need to retry posting data only when I get certain response codes. I have searched for a few options which isnt suitable for my solution. Is there any simpler way by using annotation?

1

There are 1 answers

0
Rahul Dey On BEST ANSWER

In catch block, you won't be able to get hold of the response code. Since you're interested in all 5xx, put a check for response.getStatusCode().is5xxServerError() and re-throw the exception ABCDException.class if the exceptions are well handled at the server end and returns the status code. This way you code will continue to retry for all 5xx exceptions until the maxAttempts gets exhausted.

Else, you can simply retry for HttpServerErrorException.class by replacing ABCDException.class.