首页 > 解决方案 > 在 Java 中处理 CompletableFuture 中的错误的方法

问题描述

我正在使用CompletableFuture,我遇到了以下用例:

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
}

正如你在这里看到的,我可以很容易地logexceptionally块中出错,但是如果我不希望我的程序停止并继续直到list迭代所有元素怎么办。如果有任何错误,我想记录错误并继续下一个而不是停止应用程序。

标签: javaspring-bootrx-javareactive-programmingcompletable-future

解决方案


您可以尝试捕获可以抛出异常的代码,如下所示:直接为每个项目处理异常而不阻塞 forEach 循环

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

如果您已经知道 otherFunction 可以抛出什么异常,则可以仅显式捕获该异常,并将异常保留为系统来处理其他异常。


推荐阅读