简体   繁体   English

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

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

Ok, I have methods like 好的,我有类似的方法

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

and I would like a single method that I can use that does the following such that it converts any synchronous exceptions to be put in the future 我想使用一种可以执行以下操作的方法,以便它将将来转换的所有同步异常都转换为

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

Please note that I just happend to pick #2 as the example but I would like to make that generic so I can stop typing that as in general it needs to be done once in a while to ensure you handle synch and asynch exceptions the same. 请注意,我只是碰巧选择了#2作为示例,但我想使用通用名称,因此我可以停止键入,因为一般来说,它需要偶尔执行一次,以确保您以相同的方式处理同步和异步异常。

I'm not sure this is what you're looking for, but you could create a utility function: 我不确定这是您要找的东西,但是您可以创建一个实用程序函数:

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

You'd then use it like so: 然后,您可以像这样使用它:

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

Some Notes: 一些注意事项:

  1. Used Callable because its functional method, call , can throw Exception . 之所以使用Callable是因为其功能方法call可以抛出Exception If something like Supplier was used then using it with methods that can throw checked exceptions would be messy. 如果使用诸如Supplier东西,那么将其与可能引发检查异常的方法一起使用将是混乱的。
  2. Used catch (Exception ex) rather than catch (Throwable ex) because Callable#call doesn't throw Throwable and it's usually considered bad practice to catch Error s. 使用catch (Exception ex)而不是catch (Throwable ex)因为Callable#call不会抛出Throwable ,并且通常认为捕获ErrorError的做法。 You can always change it to Throwable if you want. 如果需要,您始终可以将其更改为Throwable
  3. This utility method will return a failed future, caused by an NPE, if the callable is null ; 如果callablenull ,则此实用程序方法将返回由NPE导致的失败的将来; don't know if that's desired. 不知道这是否是理想的。

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

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