将可填写的未来中的exception映射到不同的exception类型?

我正在使用java 8的可完成期货,我希望能够采取未来抛出的exception并将其转换为另一个exception。

一旦发生exception,我试过的所有复合材料似乎都会被短路。

例如,使用scala future,我可以这样做:

scala.concurrent.Future translatedException = ask.recover(new Recover() { @Override public Object recover(final Throwable failure) throws Throwable { if (failure instanceof AskTimeoutException) { throw new ApiException(failure); } throw failure; } }, actorSystem.dispatcher()); 

我希望能够在未来的java复合块中模仿它。 这可能吗?

您可以使用CompletableFuture#handle(BiFunction) 。 例如

 CompletableFuture ask = CompletableFuture.supplyAsync(() -> { throw new IndexOutOfBoundsException(); }); CompletableFuture 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以exception完成,则translatedException将以可能已转换的exception完成。 否则,它将具有相同的成功结果值。

关于我在代码中的注释, handle方法需要一个BiFunctionapply方法未被声明为抛出Throwable 。 因此,lambda身体本身不能抛出Throwable 。 参数e的类型为Throwable因此您无法直接throw它。 如果您知道它属于该类型,则可以将其RuntimeExceptionRuntimeException ,或者可以将其包装在RuntimeExceptionthrow它。

Interesting Posts