1

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?

bootlover123
  • 111
  • 1
  • 8
  • You should check the *root cause* of the `ResourceAccessException` from the stacktrace. The endpoint might be telling you to rate limit your calls for example. – Kayaman Sep 06 '20 at 17:58
  • Looking at the stacktrace it's `Caused by: java.net.SocketException: Unexpected end of file from server`.. should I catch that exception instead of the ResourceAccessException? – bootlover123 Sep 06 '20 at 18:08
  • If you want to. Exception handling is basic Java, which you should know if you're working with Spring Boot. – Kayaman Sep 06 '20 at 18:44

0 Answers0