Home > Net >  Handle exceptions in a loop with RestTemplate
Handle exceptions in a loop with RestTemplate

Time:12-23

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?

public void method() {
    List<Objects> objects = fetchObjects();
    List<String> errorList = new ArrayList();

    for(int i=0;i<objects.size();i  ) {
      try{
        hitExternalApi(object)
      }
      catch(Exception e){
        errorList.add("Error Message")
      }
    }
    if(!errorList.isEmpty()) {
       throw new ErrorDTO(Status.BAD_REQUEST, errorList);
    }
}

  @Override
  public void hitExternalApi(Object object) { 
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<Object> request = new HttpEntity<>(object, httpHeaders);
    restTemplate.exchange(url, HttpMethod.POST, request, Void.class);
  }

@ExceptionHandler(ErrorDTO.class)
  public ResponseEntity<Problem> 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);
  }

CodePudding user response:

you can put the for loop inside a function and and call the exception after calling that function.

refer the following example for a better understanding:

BEFORE

public class ExceptionInLoop{
public static void sampleMethod(){
  String str[] = {"Mango", "Apple", "Banana", "Grapes", "Oranges"};
     try {
        for(int i=0; i<=10; i  ) {
           System.out.println(str[i]);
           System.out.println(i);
        }
     }catch (ArrayIndexOutOfBoundsException ex){
        System.out.println("Exception occurred");
  }
  System.out.println("hello");
}
public static void main(String args[]) {
  sampleMethod();
}}

AFTER

public class ExceptionInLoop{
public static void print(String str) {
  System.out.println(str);
}
public static void sampleMethod()throws ArrayIndexOutOfBoundsException   {
  String str[] = {"Mango", "Apple", "Banana", "Grapes", "Oranges"};
     for(int i=0; i<=10; i  ) {
        try {
           print(str[i]);
           System.out.println(i);
        } catch(Exception e){
        System.out.println(i);
     }
  }
}
public static void main(String args[]) {
  try{
     sampleMethod();
  }catch(ArrayIndexOutOfBoundsException e) {
     System.out.println("");
  }
}}

CodePudding user response:

You can just create an extra object for controlling the flow

public class ApiResponsePojo {
    private HttpStatus status;
    private String message;
    private String data;
}

You can use a class like this and modify it to the way you want to store the messages. you can check if there's any error through status and populate a message in the status

  • Related