gpt4 book ai didi

java 完整的 future 和异常链

转载 作者:行者123 更新时间:2023-12-01 20:26:53 26 4
gpt4 key购买 nike

我有以下代码

    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.返回可能失败或成功的恢复的 future

我知道如何在 scala 中执行此操作,但不确定如何在 java 中执行此操作。有人知道吗?

最佳答案

好吧,我想出了自己的解决方案,这是一个黑客

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());
});
}

关于java 完整的 future 和异常链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43750637/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com