今天试了下@Async注解,突然想到一个问题,如果被@Async注解修饰的方法内出现了异常,则会被捕获么?
上代码
public void test(){
try{
// 本类中调用异步方法使异步注解生效的办法
SpringUtils.getBean(ISysSchoolService.class).refreshOrganStaticBySchoolId(schoolId);
}catch (Exception e){
throw new ServiceException("刷新学校编制数据异常");
}
}
@Override
@Async
public void refreshOrganStaticBySchoolId(String schoolId) throws IllegalAccessException {
SysSchool school = this.baseMapper.selectById(schoolId);
// if(StrUtil.isNotEmpty( school.getCenterSchool() ))
throw new RuntimeException("测试异常");
}
首先调用test(),然后调用被@Async注解修饰的refreshOrganStaticBySchoolId方法,
此处是修饰在service层不是在serviceImpl层。那么test()方法会捕获到RuntimeException么?
答案是不会捕获。那该怎么处理呢?
此处放出异步注解配置类,注意此处的异步异常处理是和全局异常处理分开的。此处仅处理异步异常
package com.haoyu.framework.config;
import cn.hutool.core.util.ArrayUtil;
import com.haoyu.common.exception.ServiceException;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
/**
* 异步配置
*
* @author Lion Li
*/
@EnableAsync
@Configuration
public class AsyncConfig extends AsyncConfigurerSupport {
@Autowired
@Qualifier("scheduledExecutorService")
private ScheduledExecutorService scheduledExecutorService;
/**
* 自定义 @Async 注解使用系统线程池
*/
@Override
public Executor getAsyncExecutor() {
return scheduledExecutorService;
}
/**
* 异步执行异常处理
*/
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (throwable, method, objects) -> {
throwable.printStackTrace();
StringBuilder sb = new StringBuilder();
sb.append("Exception message - ").append(throwable.getMessage())
.append(", Method name - ").append(method.getName());
if (ArrayUtil.isNotEmpty(objects)) {
sb.append(", Parameter value - ").append(Arrays.toString(objects));
}
throw new ServiceException(sb.toString());
};
}
}
在里面进行全局捕获,最后抛出ServiceException。
此处的逻辑部分还待优化,因为即使后台可以打印日志,但是前端发接口后,此处的异步异常前端是无法感知到的。希望日后可以实现抛出异常后前端也可以感知