Spring @ExceptionHandler and multi-threading

后端 未结 1 1041
别那么骄傲
别那么骄傲 2020-12-20 17:22

I\'ve got the following controller advice:

@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(NotCachedException.class)
    @Resp         


        
相关标签:
1条回答
  • 2020-12-20 18:07

    The default exception handling machenism does not work in case of @Async Enabled. To handle exception thrown from methods annotated with @Async, you need to implement a custom AsyncExceptionHandler as.

    public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler{
        @Override
        public void handleUncaughtException(Throwable ex, Method method, Object... params) {
            // Here goes your exception handling logic.
    
        }
    }
    

    Now You need to configure this customExceptionHandler in you Application class as

    @EnableAsync
    public class Application implements AsyncConfigurer {
         @Override Executor getAsyncExecutor(){
          // your ThreadPoolTaskExecutor configuration goes here. 
    }
    
    
    @Override
    public AsyncUncaughExceptionHandler getAsyncUncaughtExceptionHandler(){
       return new AsyncExceptionHandler();
    }
    

    Note: Make sure in order to make your AsyncExceptionHandler work you need to implement AsyncConfigurer in your Application class.

    0 讨论(0)
提交回复
热议问题