如何从 CompletableFuture.whenComplete 异常块中抛出 RuntimeExcpetions?

发布于 2025-01-14 06:37:32 字数 615 浏览 3 评论 0原文

我需要将运行时异常从 CompletableFuture 异常块重新抛出到父方法,但看起来 runtimeException 正在异常块本身记录,并且不会传播回父方法。谁能告诉我我在这里做错了什么,或者这是正确的抛出方法? 我有一个如下所示的函数调用:

void method1(String msg)
{
   try
   {
    method2(msg);
    }
    catch(RuntimeException e)
    {
       throw new CustomException("");
     }
}
void method2(String msg)
{
  CompletableFuture<Void> future = asyncTask.process(msg);
  future.whenComplete((res,ex) ->
        if(ex != null)
        {
           log.error("");
           throw RuntimeException("abc");
         }
        else
         { postProcessTasks(msg);
         }
       );
}

I need to re-throw the runtime exception from the CompletableFuture Exception block to the parent method, but looks like the runtimeException is getting logged at the exception block itself and not propagating back to the parent method. Can anyone please advise/suggest me what I am doing wrong here or is this the right way to throw?
I have a function call like below :

void method1(String msg)
{
   try
   {
    method2(msg);
    }
    catch(RuntimeException e)
    {
       throw new CustomException("");
     }
}
void method2(String msg)
{
  CompletableFuture<Void> future = asyncTask.process(msg);
  future.whenComplete((res,ex) ->
        if(ex != null)
        {
           log.error("");
           throw RuntimeException("abc");
         }
        else
         { postProcessTasks(msg);
         }
       );
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你爱我像她 2025-01-21 06:37:32

调用代码不会等待 Future 完成或获取状态。这是需要添加的核心内容。

CompletableFuture<Void> future = asyncTask.process(msg)
  .thenAccept(this::postProcessTasks);
try {
  future.get();
} catch (ExecutionException e) {
  Throwable asyncException = e.getCause();
  // .. do something here
}

如果您打算将异步异常传播回调用方,那么 whenComplete 可能不是要使用的调用;它旨在处理异步调用内的异常。

The calling code doesn't wait for the Future to complete or get the status. Here's the core of what needs to be added.

CompletableFuture<Void> future = asyncTask.process(msg)
  .thenAccept(this::postProcessTasks);
try {
  future.get();
} catch (ExecutionException e) {
  Throwable asyncException = e.getCause();
  // .. do something here
}

If you intend to propagate an asynchronous Exception back to the caller then whenComplete is probably not the call to use; It is meant to handle exceptions within the asynch call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文