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



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

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

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

例如,在故意引发未捕获异常的服务中考虑此方法:

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

其输出将是:

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)
...

我该如何抓住它?

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

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

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

如果需要注入 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());
}
}

你可以在 spirngframework 中使用 aop,首先你应该配置 aop 配置。

<bean id="aspect" class="com.zhuyiren.Main"/>
<aop:config>
<aop:aspect ref="aspect">
<aop:after-throwing method="after" throwing="ex" pointcut="execution(* com.zhuyiren.service..*.*(..)),args(ex)"/>
</aop:aspect>
</aop:config>

然后你应该声明一个aspect类的方法被命名为after

public class Main {
public void after(JoinPoint point,Throwable ex){
System.out.println(point);
System.out.println("catch error:"+ex.getMessage());
}

当服务引发错误时,该方法将捕获并解决它。 在我的服务中,我做了一个算术异常,并运行应用程序,打印是:

execution(TeacherInfo com.zhuyiren.service.TeacherService.getTeacherInfo())
catch error:/ by zero

当然,上面的配置取决于 xml,也可以通过@Aspect@Pointcut@AfterThrowingAnnotation来完成。

最新更新