繁体   English   中英

如何抽象捕获的异常CompletableFutures以调用方法

[英]How to abstract catching exceptions CompletableFutures for invoking a method

好的,我有类似的方法

  1. CompletableFuture fetchCar(int id);
  2. CompletableFuture runSomething(t的东西,Extra d);
  3. CompletableFuture invoke();

我想使用一种可以执行以下操作的方法,以便它将将来转换的所有同步异常都转换为

private CompletableFuture<Void> invokeSomething(Something something) {
    CompletableFuture<Void> future;
    try {
        future = something.runSomething(t, d);
    } catch(Throwable e) {
        future = new CompletableFuture<Void>();
        future.completeExceptionally(e);
    }

    return future;
}

请注意,我只是碰巧选择了#2作为示例,但我想使用通用名称,因此我可以停止键入,因为一般来说,它需要偶尔执行一次,以确保您以相同的方式处理同步和异步异常。

我不确定这是您要找的东西,但是您可以创建一个实用程序函数:

public static <T> CompletableFuture<T> foo(Callable<CompletableFuture<T>> callable) {
    try {
        return callable.call();
    } catch (Exception ex) {
        return CompletableFuture.failedFuture(ex);
    }
}

然后,您可以像这样使用它:

Something something = ...;
CompletableFuture<Void> future = foo(() -> invokeSomthing(something));

一些注意事项:

  1. 之所以使用Callable是因为其功能方法call可以抛出Exception 如果使用诸如Supplier东西,那么将其与可能引发检查异常的方法一起使用将是混乱的。
  2. 使用catch (Exception ex)而不是catch (Throwable ex)因为Callable#call不会抛出Throwable ,并且通常认为捕获ErrorError的做法。 如果需要,您始终可以将其更改为Throwable
  3. 如果callablenull ,则此实用程序方法将返回由NPE导致的失败的将来; 不知道这是否是理想的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM