简体   繁体   English

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

[英]How To throw RuntimeExcpetions from CompletableFuture.whenComplete exception block?

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.我需要将运行时异常从 CompletableFuture Exception 块重新抛出到父方法,但看起来 runtimeException 被记录在异常块本身并且没有传播回父方法。 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:我有一个 function 电话,如下所示:

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);
         }
       );
}

The calling code doesn't wait for the Future to complete or get the status.调用代码不会等待 Future 完成或获取状态。 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;如果您打算将异步异常传播回调用者,那么whenComplete可能不是要使用的调用; It is meant to handle exceptions within the asynch call.它旨在处理异步调用的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM