我有一些静态方法,其签名如下:
public static void produceMessages() throws AeventException,
ResourceUnavailableException {...}
或
public static void doFunnyStuff(SolrIndex solrIndex) throws DifferentException {...}
我想将所有这些方法包装在 WebApplicationException
中,即 RuntimeException
,这样我就可以将它们与 CompletableFuture.runAsync()
一起使用。
到目前为止得到了这样的东西:
private void handleExceptions(Runnable r) {
try {
r.run();
} catch (Exception e) {
log.error("Exception occured", e);
throw new WebApplicationException(
Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("Internal error occurred").build());
}
}
但我仍然无法按照我想要的方式使用这些方法:
CompletableFuture.runAsync(() -> {
handleExceptions(() -> PromotionEventProducer.producePromotionUpdateMessages());
});
不幸的是,这仍然提示我在 runAsync
block 内使用 try/catch。实现将所有异常转换为可与 CompleteableFuture 一起使用的运行时异常的方法的最佳方法是什么?
最佳答案
您不能从 lambda 表达式抛出已检查的异常,同样的规则适用于 handleExceptions(() -> ...)
,它本身就是一个 lamda 表达式。
但是,您可以定义一个与 Runnable
类似但抛出异常的接口(interface)。
interface RunnableWrapper {
void run() throws Exception;
}
然后您可以定义一个方法,将检查的异常转换为运行时异常。
public void handleException(RunnableWrapper r) {
try {
r.run();
}
catch(Exception e) {
throw new CompletionException(e);
}
}
您的最终语句将如下所示,其中 foo
是一个抛出检查异常的方法。
CompletableFuture.runAsync(() -> handleException(this::foo));
关于java - 与 CompletableFuture 一起使用的异常处理方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51383087/