gpt4 book ai didi

java - 从 CompletableFuture 异常子句中抛出异常

转载 作者:行者123 更新时间:2023-11-30 10:17:00 24 4
gpt4 key购买 nike

我在处理 CompletableFuture 方法抛出的异常时遇到问题。我认为应该可以从 CompletableFuture 的异常子句中抛出异常。例如,在下面的方法中,我预计 executeWork 会抛出一个 RuntimeException,因为我在各种 exceptionally 子句中抛出一个,但是,这不起作用,我'我不确定为什么。

public void executeWork() {

service.getAllWork().thenAccept(workList -> {
for (String work: workList) {
service.getWorkDetails(work)
.thenAccept(a -> sendMessagetoQueue(work, a))
.exceptionally(t -> {
throw new RuntimeException("Error occurred looking up work details");
});
}
}).exceptionally(t -> {
throw new RuntimeException("Error occurred retrieving work list");
});
}

最佳答案

你在这里做错了几件事 ( async programming is hard ):

首先,正如@VGR 指出的那样,executeWork() 不会在出现问题时抛出异常 - 因为所有实际工作都在另一个线程上完成。 executeWork() 实际上会立即返回 - 在安排了所有工作之后但还没有完成任何工作。您可以在最后一个 CompletableFuture 上调用 get(),它将等待工作完成或失败,并抛出任何相关的异常。但这是强制同步,被认为是一种反模式。

其次,您不需要从 exceptionally() 句柄中 throw new RuntimeException() - 实际上调用时出现正确的错误( t) 在你的情况下。

查看类似的同步代码,您的示例如下所示:

try {
for (String work : service.getAllWork()) {
try {
var a = service.getWorkDetails(work);
sendMessageToQueue(work, a);
} catch (SomeException e) {
throw new RuntimeException("Error occurred looking up work details");
}
}
} catch (SomeOtherException e) {
throw new RuntimeException("Error occured retrieving work list");
}

如您所见,捕获异常并抛出 RuntimeException(这也隐藏了真正的错误)而不是让异常传播到您可以处理它们的地方没有任何好处。

exceptionally() 步骤的目的是从异常中恢复 - 例如在从用户或 IO 检索数据失败时设置默认值,或类似的事情。示例:

service.getAllWork().thenApply(workList -> workList.stream()
.map(work -> service.getWorkDetails(work)
.thenAccept(a -> sendMessageToQueue(work, a)
.exceptionally(e -> {
reportWorkFailureToQueue(work, e);
return null;
})
)
).thenCompose(futStream ->
CompletableFuture.allOf(futStream.toArray(CompletableFuture[]::new)))
.exceptionlly(e -> {
// handle getAllWork() failures here, getWorkDetail/sendMessageToQueue
// failures were resolved by the previous exceptionally and converted to null values
});

关于java - 从 CompletableFuture 异常子句中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49822669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com