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

时间:2017-08-16 06:06:09

标签: 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!");
}

它的输出将是:

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

我如何抓住这个?

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

2 个答案:

答案 0 :(得分:3)

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

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

当服务抛出错误时,该方法将捕获并解决它。 在我的服务中,我进行了ArithmeticException,并运行应用程序,print是:

Annotation

当然,上述配置取决于xml,您也可以通过@Aspect@Pointcut@AfterThrowing((c-mode . ((indent-tabs-mode . nil) (c-basic-offset . 2)))) 来完成。

答案 1 :(得分:3)

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

@Aspect
public class ExceptionHandler {

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

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

@Component
@Aspect
public class ExceptionHandler {

    @Autowired
    private SomeService someService;

    @AfterThrowing(pointcut="execution(* your.base.package..*.*(..))", throwing="ex")
    public void handleError(Exception ex) {
        someService.handleError(ex);
     }
}
相关问题