有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在哪里可以捕获spring中的非rest控制器异常?

我有spring mvc应用程序。为了捕捉异常,我使用@ExceptionHandler注释

@ControllerAdvise
public class ExceptionHandlerController {   

    @ExceptionHandler(CustomGenericException.class)
    public ModelAndView handleCustomException(CustomGenericException ex) {
            ....
    }
}

但我认为,在控制器方法调用之后,我将只捕获异常

但是如何捕获在rest上下文之外生成的异常呢?例如,生命周期回调或计划任务


共 (1) 个答案

  1. # 1 楼答案

    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。另外,不要忘记启用自动代理,在Java配置中使用@EnableAspectJAutoProxy,或者在XML配置中使用<aop:aspectj-autoproxy/>