您可以使用CompletableFuture#handle(BiFunction)
。例如
CompletableFuture<String> ask = CompletableFuture.supplyAsync(() -> {
throw new indexoutofboundsexception();
});
CompletableFuture<String> translatedException = ask.handle((r, e) -> {
if (e != null) {
if (e instanceof indexoutofboundsexception) {
throw new IllegalArgumentException();
}
throw (RuntimeException) e; // this is sketchy, handle it differently, maybe by wrapping it in a RuntimeException
}
return r;
});
如果ask
完成并带有异常,translatedException
则将完成并带有潜在转换的异常。否则,它将具有相同的成功结果值。
关于我在代码中的注释,该handle
方法期望未声明BiFunction
其apply
方法的方法抛出Throwable
。因此,lambda主体本身无法抛出Throwable
。参数e
是类型,Throwable
因此您不能throw
直接使用它。你可以将它转换为RuntimeException
,如果你知道它的那种类型的,或者你可以在一个包装它RuntimeException
和throw
那个。