如何找到CompletableFuture在特定情况下完成

ern*_*oel 4 java java-8 completable-future

我正在使用CompletableFuture,并对异常处理有疑问.

我有这样的代码,如果任何validate()或process()方法抛出异常,那么它由ExceptionHandler处理.但是,当我像这样使用CompletableFuture时,抛出的异常包含在CompletionException中.我可以知道如何确保在那里调用我的ExceptionHandler而不是获得CompletionException?

CompletableFuture<Response> response = CompletableFuture
                .supplyAsync(() -> {
                    validationService.validate(request);
                    return myService.process(request, headers);
                });
Run Code Online (Sandbox Code Playgroud)

Dea*_*ool 5

拨打电话之前get()CompletableFuture调用此方法isCompletedExceptionally,如果有异常完成将返回true

public boolean isCompletedExceptionally()
Run Code Online (Sandbox Code Playgroud)

如果此CompletableFuture以任何方式异常完成,则返回true.可能的原因包括取消,显式调用completeExceptionly,以及突然终止CompletionStage操作.

您还可以为completableFuture添加异常块,因此在执行任务时如果发生任何异常,它将执行异常,但输入参数异常

CompletableFuture<String> future = CompletableFuture.supplyAsync(()-> "Success")
                                   .exceptionally(ex->"failed");
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,如果发生任何异常,则执行supplyAsync 失败将返回,否则返回Success