Spring AOP AfterThrowing vs. Around Advice

前端 未结 2 715
悲&欢浪女
悲&欢浪女 2021-02-01 19:48

when trying to implement an Aspect, that is responsible for catching and logging a certain type of error, I initially thought this would be possible using the AfterThrowing advi

2条回答
  •  庸人自扰
    2021-02-01 20:16

    Actually, it is possible to catch exception within AfterThrowing advice as well. I know it is a convoluted example, but it works.

    @Aspect
    @Component
    class MyAspect {
    
        @Autowired
        public Worker worker;
    
        @Pointcut(value = "execution(public * com.ex*..*.*(..))")
        public void matchingAll(){}
    
        @AfterThrowing(pointcut = "matchingAll()", throwing = "e")
        public void myAdvice(RuntimeException e){
            Thread.setDefaultUncaughtExceptionHandler((t, e1) -> 
                    System.out.println("Caught " + e1.getMessage()));
            System.out.println("Worker returned " + worker.print());
        }
    }
    
    @Component
    class Worker {
    
        public static int value = 0;
    
        public int print() {
            if (value++ == 0) {
                System.out.println("Throwing exception");
                throw new RuntimeException("Hello world");
            } else {
                return value;
            }
        }
    }
    
    @SpringBootApplication
    @EnableAspectJAutoProxy
    public class AdvicesDemo {
    
        public static void main(String[] args) {
            final ConfigurableApplicationContext applicationContext = SpringApplication.run(AdvicesDemo.class);
            final Worker worker = applicationContext.getBean(Worker.class);
            System.out.println("Worker returned " + worker.print());
            System.out.println("All done");
        }
    }
    

    As you can see it is more about how to catch originally thrown exception and thus prevent its propagation back to the caller.

    Working example on GitHub (check com.example.advices package)

提交回复
热议问题