[英]How to abstract catching exceptions CompletableFutures for invoking a method
Ok, I have methods like 好的,我有类似的方法
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: 一些注意事项:
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
东西,那么将其与可能引发检查异常的方法一起使用将是混乱的。 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
,并且通常认为捕获Error
是Error
的做法。 You can always change it to Throwable
if you want. Throwable
。 callable
is null
; callable
为null
,则此实用程序方法将返回由NPE导致的失败的将来; don't know if that's desired.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.