如果第一个 CompletableFuture 失败,则不要执行第二个 CompletableFuture

Don't execute second CompletableFuture if first CompletableFuture fails

我的代码中有两个 completableFutures (cf)。 第一个 cf 的输出是第二个 cf 的输入。但是如果第一个 cf 抛出异常,我想重新抛出相同的异常并尝试在第一个 cf 失败时不执行第二个 cf。

我怎样才能做到这一点?

尝试将 2 个可运行对象组合成一个 CompletableFuture,如下所示:

CompletableFuture.runAsync(runnable1).thenRun(runnable2).join() 

(或get())

我自己找到了解决方案。

vehicleIdCachedLookupService.findVpiByChassisId(chassisId)
                .handle((identifier, ex) -> {
                    if(ex != null){
                        handleException(ex);
                    }
                    return identifier;
                })
                .thenCompose(identifier -> {
                       // do something with identifier
                }).exceptionally(ex -> {
                   log.error("Exception .. ", ex);
                   handleException(ex);
                   return null;
                });

private void handleException(Throwable ex) {
        if (ex.getCause() instanceof VPINotFoundException) {
            throw new VPINotFoundException(ex.getMessage());
        } else {
            throw new InternalServerErrorException(ex);
        }
    }

如果拿上面的代码来说,如果findVpiByChassisId抛出异常,会被handleException方法处理。 handleException如果不想执行下一阶段thenCompose可以重新抛出异常。

如果没有异常,则执行Compose阶段,return将结果返回给用户。

希望我的问题和答案都清楚!