How to catch a specific exception using retry template

1.1k views Asked by At

I am trying calling a number of services, each service is dependent on the previous call. Each call I have created my own retry logic but I have only recently discovered the Spring retry template and would like to use it.

So I've created the following retryTemplate:

  RetryTemplate retryTemplate = new RetryTemplate();
  FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
  fixedBackOffPolicy.setBackOffPeriod(4000L);
  SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
  retryPolicy.setMaxAttempts(5);
  retryTemplate.setRetryPolicy(retryPolicy);
  retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
  this.retryTemplate = retryTemplate;

And I am using the retryTemplate to call a service as such:

try
      {
         retryTemplate.execute(
            (RetryCallback<Object, Throwable>) retryContext -> *Call serivce via restTemplate etc. Returns an object of XYZ*);
      } catch (Throwable throwable)
      {
         throwable.printStackTrace();
      }

But the call sometimes throws a ResourceAccessException when we constantly bombard the service with a lot of requests (is this normal to receive when a service is under a lot stress?) hence I would like to catch it. Is it okay for me to do the following:

try
  {
     retryTemplate.execute(
        (RetryCallback<Object, Throwable>) retryContext -> Optional.of(restClient.post(restTemplate, aauiUrlLeadUri, requestBody, LeadPersistResponse.class)));
  } catch (ResourceAccessException exception)
  {
     exception.printStackTrace();
     *perform logic to handle exception*
  } catch (Throwable throwable)
  {
     throwable.printStackTrace();
  }

or can I simply put my logic in handling the excpeiton in the catch(Throwable throwable) block?

0

There are 0 answers