我有 spring mvc 应用程序。为了捕获异常,我使用了 @ExceptionHandler
注释。
@ControllerAdvise
public class ExceptionHandlerController {
@ExceptionHandler(CustomGenericException.class)
public ModelAndView handleCustomException(CustomGenericException ex) {
....
}
}
但我认为我只会在调用 Controller 方法后捕获异常。
但是如何捕获在 rest 上下文之外产生的异常呢?例如生命周期回调或计划任务。
最佳答案
But how to catch exceptions generated outside the rest context? For example lifecycle callbacks or scheduled tasks
我能想到的一个解决方案是使用 After Throwing Advice .基本思想是定义一个通知来捕获某些 bean 抛出的异常并适本地处理它们。
例如,您可以定义一个自定义注释,如:
@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
注释的方法抛出的异常。 :
@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();
}
}
为了更精细地控制方法执行,您可以使用 Around Advice , 也。也不要忘记启用自动代理,使用 @EnableAspectJAutoProxy
在 Java 配置或 <aop:aspectj-autoproxy/>
在 XML 配置中。
关于java - 我在哪里可以在 Spring 捕获非休息 Controller 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37164855/