我遇到了奇怪的行为
Java 8 CompletableFuture.exceptionally方法.如果我执行这个代码,它可以正常工作并打印出java.lang.RuntimeException
CompletableFuture<String> future = new CompletableFuture<>(); future.completeExceptionally(new RuntimeException()); future.exceptionally(e -> { System.out.println(e.getClass()); return null; });
但是如果我在未来的处理中添加了另一个步骤,那么就将异常类型更改为java.util.concurrent.CompletionException,原始异常包含在里面.
CompletableFuture<String> future = new CompletableFuture<>(); future.completeExceptionally(new RuntimeException()); future.thenApply(v-> v).exceptionally(e -> { System.out.println(e); return null; });
有什么理由要这样发生吗?在我看来,这是非常令人惊讶的.
解决方法
这个行为
is specified in the class documentation of
CompletionStage
(fourth bullet):
Method 07001 additionally allows the stage to compute a replacement result that may enable further processing by other dependent stages. In all other cases,if a stage’s computation terminates abruptly with an (unchecked) exception or error,then all dependent stages requiring its completion complete exceptionally as well,with a 07002 holding the exception as its cause.
如果您认为您可能想知道您是否特别引用的舞台失败或其中一个直接或间接的先决条件,这并不奇怪.