且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Spring Boot中捕获非MVC和非REST异常

更新时间:2022-06-18 23:47:24

如上所述,您可以定义一个方面. 使用基于Java的配置,它将看起来像这样:

As noted above, you can define an aspect. Using Java-based configuration it will look like this:

@Aspect
public class ExceptionHandler {

    @AfterThrowing(pointcut="execution(* your.base.package..*.*(..))", throwing="ex")
    public void handleError(Exception ex) {
        //handling the exception
     }
}

如果需要注入bean,请添加@Component批注:

If you need to inject a bean, add a @Component annotation:

@Aspect
@Component
public class ExceptionHandler {

    @Autowired
    private NotificationService notificationService;

    @AfterThrowing(pointcut="execution(* your.base.package..*.*(..))", throwing="ex")
    public void handleError(Exception ex) {
        notificationService.sendMessage(ex.getMessage());
     }
}