'What is the correct way to handle CompletableFuture exception?

What is the correct way to handle CompletableFuture exception in this situation?

I have a piece of code that return a CompletableFuture, but it has a potential of completeExceptionally.

I want to chain CompletableFuture, but I don't want it to execute the next method if it receive an error.

And I do not want to recover from the error either.

So my solution is throw new CompletionException(error).

public static void main(String[] args) {
    calculateThings()
            .handle((number, error) -> {
                if(error != null) {
                    throw new CompletionException(error);
                }
                // ...
            })
            .thenApply(number -> {
                // i don't want this part to execute when error happen!
                System.out.println("should not execute");
                return 100;
            })
            .whenComplete((result, error) -> {
                if(error != null) {
                    System.out.println("output this line!"); // <-- output
                }
            });
}

public static CompletableFuture<Integer> calculateThings() {
    CompletableFuture<Integer> future = new CompletableFuture<>();
    CompletableFuture.runAsync(() -> {
        future.completeExceptionally(new IllegalStateException());
    });
    return future;
}

Is this correct? I feel like this isn't a right thing to do.

I see a couple of example return failedStage or completedStage but I don't know how to unwrap the object.

enter image description here

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source