我有以下代码
return future.exceptionally(t -> {
if(t instanceof NotFoundException)
return processNotFound(responseCb, requestCtx, (NotFoundException) t, errorRoutes, null);
throw new CompletionException(t.getMessage(), t);
//in scala we would return new CompletableFuture.completeExceptionally(t) and not throw
});
其中processNotFound返回一个可能失败的CompletableFuture。
基本上,这些步骤 1.击中主要系统 2.抓住异常进行恢复 3.返回可能失败或成功的恢复未来
我知道如何在scala中执行此操作,但我不确定如何在java中执行此操作。有人知道吗?
答案 0 :(得分:2)
好吧,我提出了自己的解决方案,这是一个黑客
public static <T> ExceptionOrResult<T> convert(Throwable t, T res) {
return new ExceptionOrResult<T>(t, res);
}
/**
* This sucks as I could not find a way to compose failures in java(in scala they have a function for this)
*/
public static <T> CompletableFuture<T> composeFailure(CompletableFuture<T> future, Function<Throwable, CompletableFuture<T>> exceptionally) {
return future.handle((r, t) -> convert(t, r)).thenCompose((r) -> {
if(r.getException() == null)
return CompletableFuture.completedFuture(r.getResult());
return exceptionally.apply(r.getException());
});
}