关于捕获异步线程异常

关于Async注解异步异常捕获

    @Async
    public void test(Event event) {
      int result= 1/0;
   }
@Configuration
public class AsyncExceptionConfig implements AsyncConfigurer {
    private static final Logger log = LoggerFactory.getLogger(AsyncExceptionConfig.class);
    @Autowired
    private EventPublish eventPublish;
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }


  public  class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler{
        @Override
        public void handleUncaughtException(Throwable ex, Method method, Object... params) {
            log.error("当前方法:{},出现异常:{}",method.getName(),ex);
        }
    }
}

捕获线程池中线程异常

 ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(threadPoolName + "-%d").build();
  ExecutorService executorService = TtlExecutors.getTtlExecutorService(new ThreadPoolExecutor(coreSize, poolSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(blockQueueSize), threadFactory){
                // 捕获线程异常,重新发布事件
                @Override
                protected void afterExecute(Runnable r, Throwable t) {
                    super.afterExecute(r, t);
                    if(t!= null){
                       // do something
                        logger.error("execute",t);
                    }
                    if(r instanceof FutureTask){
                        try {
                            Future future = (Future) r;
                            future.get();
                        } catch (Exception e) {
                            // do something
                            logger.error("future里面取执行异常", e);
                        }
                    }
                }
            });

你可能感兴趣的:(exception,android,java,bug,log4j)