java 完整的 future 和异常链

标签 java exception completable-future

我有以下代码

    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/

相关文章:

c++ - 将主应用程序对象包含在 try-catch block 中会捕获所有崩溃吗?

java - 如何使用 CompletableFuture 返回一个值

java - 如何在谷歌浏览器中运行 java jar 小程序?

java - OOP 如何将击败的敌人的钱添加到主角的包里?

Javac Ant 构建错误

java - 如何将 CompletableFuture<Stream<T>> 转换为 Stream<CompletableFuture<T>>?

java - 运行线程时的异常处理

java - Spring表单未提交

ios - 崩溃问题 : iOS 12. 0.1 ( 16A404 ), App 自动关闭

python - Else子句在Python异常处理中的应用