Search code examples
springspring-bootspring-aop

Spring AOP for exception handling


I am calling a rest end point like below. I need to send email if rest call fails i,e if exception occurs in m1 method or response==null.

    Foo m1(String s) {
    
        ResponseEntity<Foo> response = restTemplate
          .exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
        
          response.getbody();
}

Solution

  • You can achieve it using annotation @AfterThrowing,

    AspectJ @AfterThrowing advice is executed after a join point does not complete normally and end up throwing an exception.

    In your case, you can create an aspect and implement logic to send email there

    @Aspect
    public class LoggingAspect {
    
        @AfterThrowing ("execution(* com.demo.app.service.impl.demoImpl.*(..))")
        public void doSomethingAfterThrowingAllMethods() throws Throwable { ... }
    }