[英]Handling CompletableFuture exceptions in controller
我正在尝试为我正在运行的项目进入CompletableFuture
class ,我在这里遇到了一些问题:
有以下方法:通过ID或hash尝试查找会话; 如果没有找到,它会抛出异常。 到目前为止,一切都很好。
public ConversationOutput getConversationByIdOrHash(String conversationIdOrHash)
throws ConversationNotFoundException {
Conversation conversation = this.conversationRepository.getByIdOrHash(conversationIdOrHash);
if (conversation == null) {
throw new ConversationNotFoundException(conversationIdOrHash);
}
return this.modelMapper.map(conversation, ConversationOutput.class);
}
请注意,我正在从我的方法签名中抛出ConversationNotFoundException
。 我的 SpringBoot controller 正在对此异常做出反应,并且从一开始就一切正常。
我想要做的是使它成为CompletableFuture
返回并实际抛出异常,类似于:
public CompletableFuture<ConversationOutput> getConversationByIdOrHashAsync(String conversationIdOrHash)
throws ConversationNotFoundException {
return CompletableFuture.supplyAsync(() -> this.getConversationByIdOrHash(conversationIdOrHash));
}
我看过人们使用exceptionally
处理异常的帖子,但我真正想做的是将它扔到我的 controller 并让它处理它。 关于如何制作的任何建议?
谢谢你们!
问题是您是否关心CompletableFuture
的结果。 CompletableFuture
就像一个特殊的任务,它在其他线程上处理。 如果您不调用.join()
,您将不会收到CompletableFuture
的结果。 如果发生任何异常,此方法也将传播异常。 但是,它等待CompletableFuture
完成并阻止请求。 但是,没有等待就无法从CompletableFuture
内部获取异常,您必须像对待其他任务一样对待它。
如果成功,您可以传递已完成的未来,以及失败的未来以及您的自定义异常。
public CompletableFuture<ConversationOutput> getConversationByIdOrHashAsync(String conversationIdOrHash) {
try {
return CompletableFuture.completedFuture(this.getConversationByIdOrHash(conversationIdOrHash));
} catch (ConversationNotFoundException e) {
return CompletableFuture.failedFuture(e);
}
}
然后在您的 controller 级别,您可以处理异常。
final CompletableFuture<ConversationOutput> future = getConversationByIdOrHashAsync("idOrHash");
future.whenComplete((r, e) -> {
if (e != null) {
if (e instanceof ConversationNotFoundException) {
//handling
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.