.a.i.SimpleAsyncUncaughtExceptionHandler : Unexpected exception occurred invoking async method ...

備忘録。

@Async で非同期に処理するメソッドの中で例外が発生した場合、表題のようなエラーが出力される。

2022-01-26 22:44:58.608 ERROR 3401 --- [         task-1] .a.i.SimpleAsyncUncaughtExceptionHandler : Unexpected exception occurred invoking async method: public void com.example.SampleService.execute()

デフォルトでは、SimpleAsyncUncaughtExceptionHandler クラスでハンドリングされるため。以下抜粋。

public void handleUncaughtException(Throwable ex, Method method, Object... params) {
    if (logger.isErrorEnabled()) {
        logger.error("Unexpected exception occurred invoking async method: " + method, ex);
    }
}

この例外をハンドリングする場合は、AsyncUncaughtExceptionHandler インタフェースを実装したクラスを用意する。

@Component
public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
    @Override
    public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
        log.warn("Unexpected asynchronous exception!!");
    }
}
@Configuration
public class Config extends AsyncConfigurerSupport {
    @Autowired
    AsyncExceptionHandler asyncExceptionHandler;
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return asyncExceptionHandler;
    }
}
2022-01-26 23:12:00.616  WARN 3846 --- [         task-1] c.e.AsyncExceptionHandler  : Unexpected asynchronous exception!!

現場からは以上です。