关于async里面try/catch的一个问题
2017-08-30 本文已影响0人
wyatt_plus
@Async注释属于异步调用,try/catch 不能捕获到异常。
总结
1.try…catch是同步代码
2.异步,已经脱离了当前当前的主线程; 可以想象成在一个新的定时任务里去执行的;只是能与主线程共享内存,堆栈等;
代码示范:
1.调用方法
public void recordExcute(PartnerlendingRecordDomain domain) {
try {
partnerLendingService.excuteAutoMatch(domain);
} catch (Exception e) {
e.printStackTrace();
/* 状态 0-待处理 1-处理完成2-处理失败 */
// 更新partnerlendingrecord记录
domain.setStatus(2);
domain.setUpdateTime(new Date());
partnerlendingRecordService.update(domain);
logger.error(String.format("合伙人分配列表定时任务! job AgreementId: %s", domain.getAgreementId()));
}
}
2.接口service方法
public interface IPartnerLendingService {
@Async
void excuteAutoMatch(PartnerlendingRecordDomain partnerlendingrecorddomain);
}
3.模拟测试
故意将对象设为空指针异常
java.lang.NullPointerException: null
at com.zx.loan.core.loan.service.impl.PartnerLendingServiceImpl.excuteAutoMatch(PartnerLendingServiceImpl.java:452)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:108)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
异常能捕获到,但是并不走try catch。此处会让人疑惑,为什么了?
以为try catch 属于同步捕获,所以只要将@Async取消掉就行,就能正常捕获。