CompletableFuture异常处理:前序任务失败时如何不执行后序任务
问题原因
你使用的whenComplete方法的设计目标就是无论上游CompletableFuture是正常完成还是异常终止,都会执行传入的回调逻辑,通常用于执行资源释放、状态记录这类不管任务成功失败都要完成的收尾操作,因此不符合“A失败则B不运行”的要求。
解决方案
有两类常用实现方式可以满足你的需求:
方案1:使用then*系列回调方法(推荐)
CompletableFuture提供的thenRun、thenAccept、thenApply等回调方法,仅会在上游任务正常完成时触发执行,若上游抛出异常,下游回调会直接跳过,异常会沿调用链向下传递。
- 若
doB不需要使用doA的返回结果,且无返回值,使用thenRun:
CompletableFuture<Void> f = CompletableFuture.supplyAsync(() -> doA(arg)) .thenRun(() -> doB(arg));
- 若
doB需要使用doA的返回结果,且无返回值,使用thenAccept:
CompletableFuture<Void> f = CompletableFuture.supplyAsync(() -> doA(arg)) .thenAccept(resultA -> doB(arg, resultA));
- 若
doB有返回值,需要获取doB的执行结果,使用thenApply:
CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> doA(arg)) .thenApply(resultA -> doB(arg, resultA));
方案2:在whenComplete中增加异常判断
如果需要保留现有whenComplete的写法,只需在回调中先判断上游是否抛出异常,仅无异常时执行doB即可:
CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> doA(arg)) .whenComplete((resultA, throwable) -> { if (throwable == null) { doB(arg); } });
内容的提问来源于stack exchange,提问作者user1475172
相关产品推荐
相关产品推荐

