title: Handle exceptions in a loop with RestTemplate
body: <p>I have a list of objects and for each object, I need to hit external API using the RestTemplate. To do that I am using the for loop with try-catch block. In case external API does respond with 4xx, 5xx status code I need to create the list of errors and throw the custom exception which is handled using the exception handler to send client-friendly messages which also send the email notifications. The requirement is to remove the try-catch block and hit the external API in a loop and create the list of errors and check if the error list is not empty throw the exception and send all the error messages at once in the email notification using the exception handler method handleApplicationErrors. But I believe when any exception will occur for loop will be a break and I will not be able to create a list of error messages without a try-catch block, is there any possible way to do it?</p>
  <pre><code>public void method() {
      List&lt;Objects&gt; objects = fetchObjects();
      List&lt;String&gt; errorList = new ArrayList();
  
      for(int i=0;i&lt;objects.size();i++) {
        try{
          hitExternalApi(object)
        }
        catch(Exception e){
          errorList.add(&quot;Error Message&quot;)
        }
      }
      if(!errorList.isEmpty()) {
         throw new ErrorDTO(Status.BAD_REQUEST, errorList);
      }
  }
  
    @Override
    public void hitExternalApi(Object object) { 
      httpHeaders.setContentType(MediaType.APPLICATION_JSON);
      HttpEntity&lt;Object&gt; request = new HttpEntity&lt;&gt;(object, httpHeaders);
      restTemplate.exchange(url, HttpMethod.POST, request, Void.class);
    }
  
  @ExceptionHandler(ErrorDTO.class)
    public ResponseEntity&lt;Problem&gt; handleApplicationErrors(NativeWebRequest request, ErrorDTO error) {
      notificationService.sendNotification(error.getErrors());
      Problem problem =
          Problem.builder()
              .withStatus(error.getStatus())
              .withTitle(error.getMessage())
              .withDetail(error.getErrors().toString())
              .build();
      return create(error, problem, request);
    }
  </code></pre>