简体   繁体   English

如何在Spring Boot异步功能中处理未捕获的异常?

[英]How to handle uncaught exceptions in Spring boot async function?

The async function, in case of any uncaught exception stops without throwing out any lines of error on the console. 如果发生任何未捕获的异常,则异步功能将停止,而不会在控制台上抛出任何错误行。 If the function is not marked async, then the logs corresponding to it are printed. 如果该功能未标记为异步,则将打印与该功能相对应的日志。

@Async  
public CompletableFuture<?> AsyncManager() {
    logger.info("Executing method asynchronously - " + Thread.currentThread().getName());

    HashMap<String, String> map = new HashMap<>();
    map.get("Hello").length();

    return CompletableFuture.completedFuture(map); 
  }

The above code is a snippet. 上面的代码是一个片段。 I understand that it will throw null pointer exception and i have deliberately set it up that way. 我知道它将抛出空指针异常,并且我已经故意以这种方式进行设置。

ERROR -Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; 路径为[]的上下文中Servlet [dispatcherServlet]的错误-Servlet.service()引发异常[请求处理失败; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException: null 嵌套异常是java.lang.NullPointerException],其根本原因是java.lang.NullPointerException:null

When the function is marked @Async it shows nothing at the line ie 当该功能标记为@Async时,该行什么也没有显示,即

map.get("Hello").length();

I understand that this might be because the exceptions are not propagated to the main thread. 我了解这可能是因为异常未传播到主线程。 How do i handle the exceptions in async functions? 如何处理异步功能中的异常?

将整个代码放在try and catch(ex exException)中并记录该异常。

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

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