Spring Async Uncaught Exception handler

后端 未结 4 1386
不思量自难忘°
不思量自难忘° 2020-12-09 09:08
@Override
@Async
public void asyncExceptionTest() {
    int i=1/0;
}

How can I log this using Spring Async framework without having to put try catc

4条回答
  •  独厮守ぢ
    2020-12-09 09:50

    First off all, you should create a custom exception handler class like following;

    @Component
    public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
    
            private final Logger logger = LoggerFactory.getLogger(AsyncExceptionHandler.class);
    
            @Override
            public void handleUncaughtException(Throwable ex, Method method, Object... params) {
                logger.error("Unexpected asynchronous exception at : "
                        + method.getDeclaringClass().getName() + "." + method.getName(), ex);
            }
    
        }
    

    After that, you should set your customized exception handler class in your configuration like following;

    @Configuration
    @EnableAsync
    public class AsyncConfig extends AsyncConfigurerSupport {
    
        @Autowired
        private AsyncExceptionHandler asyncExceptionHandler;
    
        @Override
        public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
            return asyncExceptionHandler;
        }
    
    }
    

    Note : Injectable exception handler is an option. You can create a new instance for every exception. My advice is using Injection for exception handler class, because spring's default scope is singleton so there is no need to create new instance for every exception.

提交回复
热议问题