【问题标题】:Letting CompletableFuture exceptionally() handle a supplyAsync() Exception让 CompletableFuture exceptionly() 处理 supplyAsync() 异常
【发布时间】:2020-11-24 13:25:21
【问题描述】:

问题很简单:我正在寻找一种优雅的方式来使用CompletableFuture#exceptionallyCompletableFuture#supplyAsync。这是行不通的:

private void doesNotCompile() {
    CompletableFuture<String> sad = CompletableFuture
            .supplyAsync(() -> throwSomething())
            .exceptionally(Throwable::getMessage);
}

private String throwSomething() throws Exception {
    throw new Exception();
}

我认为exceptionally() 背后的想法正是为了处理抛出Exception 的情况。但是,如果我这样做,它会起作用:

private void compiles() {
    CompletableFuture<String> thisIsFine = CompletableFuture.supplyAsync(() -> {
        try {
            throwSomething();
            return "";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }).exceptionally(Throwable::getMessage);
}

我可以使用它,但它看起来很糟糕并且使事情更难维护。有没有不需要将所有Exception 转换为RuntimeException 的方法来保持这种清洁?

【问题讨论】:

  • 如果要使用第一个选项,只需将throwSomething()的返回类型从void更改为String即可。
  • 对不起,这是我在写这个简化版本时的一个错误。我根据您的建议编辑了 OP,指出它不能解决问题。
  • 啊,对不起。我忘了你在处理 checked 异常。基本上,问题是Supplier#get() 没有声明为抛出Exception。也许这里的东西会对你有所帮助:Java 8 Lambda function that throws exception?.

标签: java exception completable-future


【解决方案1】:

这可能不是一个超级流行的库,但我们在内部使用它(有时我也在那里做一些工作;虽然很小):NoException。真的,真的很适合我的口味。这不是它唯一的功能,但绝对涵盖了您的用例:

这是一个示例:

import com.machinezoo.noexception.Exceptions;
import java.util.concurrent.CompletableFuture;

public class SO64937499 {

    public static void main(String[] args) {
        CompletableFuture<String> sad = CompletableFuture
            .supplyAsync(Exceptions.sneak().supplier(SO64937499::throwSomething))
            .exceptionally(Throwable::getMessage);
    }

    private static String throwSomething() throws Exception {
        throw new Exception();
    }
}

或者您可以自己创建这些:

final class CheckedSupplier<T> implements Supplier<T> {

    private final SupplierThatThrows<T> supplier;

    CheckedSupplier(SupplierThatThrows<T> supplier) {
        this.supplier = supplier;
    }

    @Override
    public T get() {
        try {
            return supplier.get();
        } catch (Throwable exception) {
            throw new RuntimeException(exception);
        }
    }
}



@FunctionalInterface
interface SupplierThatThrows<T> {

    T get() throws Throwable;
}

及用法:

 CompletableFuture<String> sad = CompletableFuture
        .supplyAsync(new CheckedSupplier<>(SO64937499::throwSomething))
        .exceptionally(Throwable::getMessage);

【讨论】:

  • 虽然这看起来是一个不错的解决方案,但出于安全原因,我们只能使用不托管此类库的私有关系。
  • @payne 见编辑
  • 看起来好多了。但是,这不会让我使用异常作为论据,对吧?因为我需要检查 Exception 的类型以不同的方式处理不同的情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-27
  • 1970-01-01
  • 1970-01-01
  • 2018-06-17
  • 2019-05-03
相关资源
最近更新 更多