Spring 用于异常处理的 AOP

Spring AOP for exception handling

我正在调用如下所示的休息终点。 如果 rest 调用失败,我需要发送电子邮件,例如,如果 m1 方法或 response==null 中发生异常。

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

你可以使用注解@AfterThrowing实现,

AspectJ @AfterThrowing 建议在连接点未正常完成并最终抛出异常后执行。

在你的情况下,你可以创建一个方面并实现逻辑以在那里发送电子邮件

@Aspect
public class LoggingAspect {

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