1
votes

I'm struggling with understanding @Retryable. What I need is to retry 3 times when I get 5xx Exception and if retry also fails then throw a custom exception in the recovery method. And if some other exception is thrown then catch it and throw a custom exception.

@Retryable(value = HttpServerErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 3000))
public String callToService(String key) {
        String response;
        try {
            response =  //assume a service call here
            
        }catch (Exception ex) {
            throw new customException("some message");
        }
        return response;
}
    
@Recover
public void retryFailed(HttpServerErrorException httpServerErrorException) {
    throw new customException("some message");
}
1

1 Answers

0
votes

In your case as you have added: @Retryable(value = HttpServerErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 3000))

The @Retryable is used with:

  1. value = HttpServerErrorException.class, so your method will be retried only if HttpServerErrorException is occure/thrown from your method code, and Note: if any other exception thrown retry will not be done, and recover method will also not be invoked, as recover method is only invoked with exception mentioned in value in @Retryable.
  2. maxAttempts = 3, so it will retry executing your method 3 times by maximum
  3. backoff = @Backoff(delay = 3000), so it will keep a delay of 3000ms in between retry.
  4. And after retrying 3 times, if your method still not working, your method with @Recover will be envoked with the HttpServerErrorException

I hope it make sense and help yo understand the concept of @Retryable

Now to implement what you want you need to implement it as below:

@Retryable(value = HttpServerErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 3000))
public String callToService(String key) {
        String response;
        try {
            response =  //assume a service call here
        } catch (HttpServerErrorException httpServerErrorException) {
            throw httpServerErrorException;
        } catch (Exception ex) {
            throw new CustomException("some message");
        }
        return response;
}
    
@Recover
public void retryFailed(HttpServerErrorException httpServerErrorException) {
    //do whatever you want here, when HttpServerErrorException occured more than 3 times
}