Spring Async method hides exceptions

2019-07-11 20:03发布

问题:

I have a strange issue with Async methods. If I run it in async way and its job throws some particular exception, it doesn't show it and simply stop the execution (no catch, no log).

I found it working with jasperreport. This is the fault block code:

JasperPrint jp1=null;
try{
    jp1 = JasperFillManager.fillReport(reportD1, params, new JRBeanCollectionDataSource(ingressi));
}catch(Exception e){
    log.error(e);
    e.printStackTrace();
    throw e;
}

If this code is inside an Async annotated method it doesn't throw the exception and doesn't log (simply stops the execution). If I remove the Async annotation, it throws this:

java.lang.ClassNotFoundException: org.apache.commons.collections.map.ReferenceMap

My trouble is not the exception itself, but why async method doesn't catch it?

回答1:

Which method is @Async exactly? If you are running an asynchronous method you should always favour a Futureas result type. If you provide a void method, there's no way to transmit any sort of exception that would happen in the (asynchronous) thread.

There is catch for void method. Long story short: Spring Framework 4.1 allows you to register an exception handler for that kind of things, check SPR-8995. 4.1.RC1 will be available shortly if you want to try.