在spring哪里可以捕获非rest控制器exception?
我有spring mvc应用程序。 为了捕获exception,我使用了@ExceptionHandler
注释。
@ControllerAdvise public class ExceptionHandlerController { @ExceptionHandler(CustomGenericException.class) public ModelAndView handleCustomException(CustomGenericException ex) { .... } }
但我认为在控制器方法调用之后我只会捕获exception。
但是如何捕获在其余环境之外生成的exception? 例如生命周期回调或计划任务。
但是如何捕获在其余环境之外生成的exception? 例如生命周期回调或计划任务
我能想到的一个解决方案是使用After Throwing Advice 。 基本思想是定义一个建议,它将捕获某些bean抛出的exception并适当地处理它们。
例如,您可以定义自定义注释,如:
@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Handled {}
并使用该注释来标记应该建议的方法。 然后,您可以使用此批注对工作进行注释:
@Component public class SomeJob { @Handled @Scheduled(fixedRate = 5000) public void doSomething() { if (Math.random() < 0.5) throw new RuntimeException(); System.out.println("I escaped!"); } }
最后定义一个建议来处理由@Handled
注释的方法抛出的exception:
@Aspect @Component public class ExceptionHandlerAspect { @Pointcut("@annotation(com.so.Handled)") public void handledMethods() {} @AfterThrowing(pointcut = "handledMethods()", throwing = "ex") public void handleTheException(Exception ex) { // Do something useful ex.printStackTrace(); } }
对于方法执行的更细粒度控制,您也可以使用“ 周围建议” 。 另外,不要忘记在Java配置中使用@EnableAspectJAutoProxy
或在XML配置中使用
启用自动@EnableAspectJAutoProxy
。