问题
CompletableFuture.completedFuture() returns a CompletedFuture
that is already completed with the given value.
How do we construct a CompletableFuture
that is already completed exceptionally?
Meaning, instead of returning a value I want the future to throw an exception.
回答1:
Unlike Java 9 and later, Java 8 does not provide a static factory method for this scenario. The default constructor can be used instead:
CompletableFuture<T> future = new CompletableFuture<>();
future.completeExceptionally(exception);
回答2:
Java 9 provides CompletableFuture.failedFuture(Throwable ex) that does exactly that.
来源:https://stackoverflow.com/questions/49116855/completablefuture-already-completed-with-an-exception