Search code examples
javaspring-bootrx-javareactive-programmingcompletable-future

Ways to handle error in CompletableFuture in Java


I was working with CompletableFuture and I came across the following use case:

public void someFunction () {
  CompletableFuture.runAsync(() -> computations())
  .exceptionally((err) -> {
    log.info(err + "");
    return null;
  });
}

public void computations() {
  
  list.stream.forEach(() -> otherFunction());
  
}

public void otherFunction() {
  //computations which can throw some error
}

As you can see here, I can easily log the error in exceptionally block but what if I don't want my program to halt and continue until all the elements of list is iterated. I want to log the error if there is any and proceed to the next and not halt the application.


Solution

  • You can try catch the code that can throw the Exception as follow: to handle the exception directly for each item without blocking the forEach loop

    public void otherFunction() {
       try {
         //computations which can throw some error
       } catch (Exception e) {
         // Log and handle error without blocking analysis for following items
       }
     }
    

    If you already know what exception can be thrown by otherFunction you can explicitly catch only that exception and leave exceptionally as a system to handle other exceptions.