简体   繁体   中英

How to find CompletableFuture completed execeptionally

I am using CompletableFuture and have a question on exception handling.

I have a code like this, if any of validate() or process() method throws an exception then it is handled by the ExceptionHandler. However when I am using the CompletableFuture like this then the exception thrown is wrapped in CompletionException. May I know how can I make sure that my ExceptionHandler is called there instead of getting CompletionException?

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

Before calling get() on CompletableFuture call this method isCompletedExceptionally , will return true if it completes with exception

public boolean isCompletedExceptionally()

Returns true if this CompletableFuture completed exceptionally, in any way. Possible causes include cancellation, explicit invocation of completeExceptionally, and abrupt termination of a CompletionStage action.

You can also add exceptional block for the completableFuture, so while executing task if any exception occurs it will execute the exceptionally with exception an input argument

CompletableFuture<String> future = CompletableFuture.supplyAsync(()-> "Success")
                                   .exceptionally(ex->"failed");

In the above example if any exception occurs executing supplyAsync failed will return or else Success is returned

Got it, by calling the following code, it will solve my problem

try {
            response.join();
        }
        catch(CompletionException ex) {
            try {
                throw ex.getCause();
            }

            catch(Throwable impossible) {
                throw impossible;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM