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

Mit*_*dge 6 java spring raygun

我已经能够找到无数关于如何在 Spring MVC 或 Spring REST 中捕获未处理的异常的教程,但我想知道的是如何在不使用 Spring Web 框架的情况捕获未处理的异常

我正在编写一个没有 Web 组件的应用程序,并且我不打算仅为异常处理而导入 Spring Web。

@Service抛出未处理的异常时,我需要捕获它,以便我可以将其正确记录到Raygun

例如,考虑一个故意抛出未捕获异常的服务中的这个方法:

@Scheduled(fixedDelay = 100)
public void doSomething() {
    throw new RuntimeException("Uh oh!");
}
Run Code Online (Sandbox Code Playgroud)

它的输出将是:

2017-08-16 00:19:40.202 ERROR 91168 --- [pool-1-thread-1] o.s.s.s.TaskUtils$LoggingErrorHandler    : Unexpected error occurred in scheduled task.

java.lang.RuntimeException: Uh oh!
    at com.mitchtalmadge.example.ExampleService.doSomething(ClassSyncService.java:48) ~[classes/:na]
    at com.mitchtalmadge.example.ExampleService$$FastClassBySpringCGLIB$$1dd464d8.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:669)
    ...
Run Code Online (Sandbox Code Playgroud)

我怎么抓住它?

没有简单的方法可以做到这一点吗?

Ily*_*nko 6

您可以定义一个方面。使用基于 Java 的配置,它将如下所示:

@Aspect
public class ExceptionHandler {

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

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

@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());
     }
}
Run Code Online (Sandbox Code Playgroud)