@Override
@Async
public void asyncExceptionTest() {
int i=1/0;
}
如何使用Spring Async框架记录此内容而无需在每个异步方法中放置try catch?它似乎没有像DefaultUncaughtExceptionHandler
那样正常传递。
答案 0 :(得分:19)
@Configuration
@EnableAsync
public class ExampleConfig implements AsyncConfigurer {
@Bean
public Runnable testExec() {
return new TestExec();
}
@Override
public Executor getAsyncExecutor() {
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(7);
executor.setMaxPoolSize(42);
executor.setQueueCapacity(11);
executor.setThreadNamePrefix("MyExecutor-");
executor.initialize();
return new HandlingExecutor(executor);
}
}
public class HandlingExecutor implements AsyncTaskExecutor {
private AsyncTaskExecutor executor;
public HandlingExecutor(AsyncTaskExecutor executor) {
this.executor = executor;
}
@Override
public void execute(Runnable task) {
executor.execute(task);
}
@Override
public void execute(Runnable task, long startTimeout) {
executor.execute(createWrappedRunnable(task), startTimeout);
}
@Override
public Future<?> submit(Runnable task) {
return executor.submit(createWrappedRunnable(task));
}
@Override
public <T> Future<T> submit(final Callable<T> task) {
return executor.submit(createCallable(task));
}
private <T> Callable<T> createCallable(final Callable<T> task) {
return new Callable<T>() {
@Override
public T call() throws Exception {
try {
return task.call();
} catch (Exception e) {
handle(e);
throw e;
}
}
};
}
private Runnable createWrappedRunnable(final Runnable task) {
return new Runnable() {
@Override
public void run() {
try {
task.run();
} catch (Exception e) {
handle(e);
}
}
};
}
private void handle(Exception e) {
System.out.println("CAUGHT!");
}
}
答案 1 :(得分:15)
更新:自春季4.1以来
从Spring 4.1开始,@Async
void
方法可能会AsyncUncaughtExceptionHandler。
Spring Reference Doc,Chapter 34.4.5 Exception management with @Async
...但是,对于void返回类型,异常未被捕获且无法传输。对于这些情况,可以提供AsyncUncaughtExceptionHandler来处理此类异常。
默认情况下,只会记录异常。可以通过AsyncConfigurer或任务:注释驱动的XML元素定义自定义AsyncUncaughtExceptionHandler。
(这个功能是在DD提出一个支持请求后引入的:https://jira.spring.io/browse/SPR-8995,请参阅此答案的评论)
在春季4.1之前
看起来像是一个缺少的功能,如何处理void
返回@Async
方法的异常。 (我在参考或java文档中找不到任何提示)
我能想象出一个解决方案:尝试使用AspectJ来编写一些包含所有记录异常的@Async
方法的包装器。
对于日志术语,我建议在spring bug tracker中创建一个freature请求。
答案 2 :(得分:6)
首先,您应该创建一个自定义异常处理程序类,如下所示;
@Component
public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(AsyncExceptionHandler.class);
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
logger.error("Unexpected asynchronous exception at : "
+ method.getDeclaringClass().getName() + "." + method.getName(), ex);
}
}
之后,您应该在配置中设置自定义异常处理程序类,如下所示;
@Configuration
@EnableAsync
public class AsyncConfig extends AsyncConfigurerSupport {
@Autowired
private AsyncExceptionHandler asyncExceptionHandler;
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return asyncExceptionHandler;
}
}
注意:可注入异常处理程序是一个选项。您可以为每个例外创建一个新实例。我的建议是使用Injection for exception handler class,因为spring的默认范围是singleton,因此不需要为每个异常创建新实例。
答案 3 :(得分:0)
您可以使用标准的 Spring AOP 方法
@Aspect
@Component
@Slf4j
public class AsyncHandler {
@Around("@annotation(org.springframework.scheduling.annotation.Async)")
private Object handle(ProceedingJoinPoint pjp) throws Throwable {
try {
Object retVal = pjp.proceed();
return retVal;
} catch (Throwable e) {
log.error("in ASYNC, method: " + pjp.getSignature().toLongString() + ", args: " + AppStringUtils.transformToWellFormattedJsonString(pjp.getArgs()) + ", exception: "+ e, e);
throw e;
}
}
}