@Async will not call by @ControllerAdvice for global exception

Viewed 767

I have a service class with @Async method and If it's calling method throwing any exception then the @ControllerAdvice will not call for global exception handling. But for other classes and services it will call advice and sending email properly.

@Service
public class FileScanServiceImpl implements FileScanService {
    @Override
    @Async
    public void scanFileScheduler() throws MQException {
    try{
        messageProducer.putFileNameToMQ(fileName);
        } catch (Exception e) {
            ExceptionUtility.handleException(e, currentFile);
        }
  }

The ExceptionUtility is used for checking instance on exception and doing some functionality there and throwing custom exception.

public static void handleException(Exception e throws MQException {
        String errMsg = "";
        if (e instanceof MQException) {
            // some functionality
            throw new MQException(subject, errMsg);
        }
    }

And this is my @ControlleAdvice

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MQException.class)
    @ResponseBody
    public void handleMQException(HttpServletRequest request, MQException ex) {
     // send email
    }
}

It there any solution for @Async which will call @ControllerAdvice for global exception, also the existing functionality will not break.

1 Answers

@ExceptionHandler was created to catch only "synchronous exceptions". If it had the ability to catch exceptions from asynchronous threads, then when several threads start and if any of them fail, the request to the server would be interrupted completely and the system could remain in an inconsistent state (due to many other active threads generated by this request)

For handling asynchronous exceptions Spring has the AsyncUncaughtExceptionHandler interface:

public class YourAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

    @Override
    public void handleUncaughtException(Throwable ex, Method method, Object... params) {
        
       // Your exception handling logic
    
    }
}

More information can be found here in the Exceptions section: https://www.baeldung.com/spring-async

Related