@Override
@Async
public void asyncExceptionTest() {
int i=1/0;
}
How can I log this using Spring Async framework without having to put try catch around every async method? It doesn't seem to pass to the DefaultUncaughtExceptionHandler
like normal.
First off all, you should create a custom exception handler class like following;
After that, you should set your customized exception handler class in your configuration like following;
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.
Update: Since Spring 4.1
Since Spring 4.1 It is possible to have an AsyncUncaughtExceptionHandler for
@Async
void
methods.Spring Reference Doc, Chapter 34.4.5 Exception management with @Async
(This feature was introduced after DD raised an impovement request: https://jira.spring.io/browse/SPR-8995 , see comments of this answer)
Before Spring 4.1
Looks like an missing feature how to handle exceptions of an
void
returning@Async
Method. (I can not find any hint in the reference or java doc)What I can imagine of an solution: Try to use AspectJ to write some kind of wrapper arround all
@Async
methods that log the exceptions.For the log term, I would recommend to create an freature request in the spring bug tracker.
You can use standard Spring AOP approach