繁体   English   中英

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

[英]How to catch non-MVC and non-REST exceptions in Spring Boot

我已经能够找到无数关于如何在 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());
}

当服务抛出错误时,该方法将捕获并解决它。 在我的服务中,我创建了一个 ArithmeticException,然后运行该应用程序,打印结果是:

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

当然,上面的配置是依赖于XML,你也可以做到这一点通过Annotation ,如@Aspect@Pointcut@AfterThrowing

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM