在春天哪里可以捕获非休息控制器异常? [英] Where can I catch non rest controller exceptions in spring?

查看:131
本文介绍了在春天哪里可以捕获非休息控制器异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有spring mvc应用程序。要捕获异常,我使用 @ExceptionHandler 注释。

I have the spring mvc application. To catch exceptions I use @ExceptionHandler annotation.

@ControllerAdvise
public class ExceptionHandlerController {   

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

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

But I think that I will catch only exceptions after controller methods invocations.

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

But how to catch exceptions generated outside the rest context? For example lifecycle callbacks or scheduled tasks.

推荐答案


但是如何捕获在其余上下文之外生成的异常?对于
示例生命周期回调或计划任务

But how to catch exceptions generated outside the rest context? For example lifecycle callbacks or scheduled tasks

我能想到的一个解决方案是使用 投掷建议后 。基本思想是定义一个建议,它将捕获某些bean抛出的异常并适当地处理它们。

One solution that I can think of it, is to use a After Throwing Advice. The basic idea is to define an advice that would caught exceptions thrown by some beans and handle them appropriately.

例如,您可以定义一个自定义注释,如:

For example, you could define a custom annotation like:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Handled {}

并使用该注释标记应该建议的方法。然后你可以使用这个注释来注释你的工作:

And use that annotation to mark methods that should be advised. Then you can annotate your, say, jobs with this annotation:

@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 注释:

And finally define an advice that handles exceptions thrown by methods annotated with @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配置或< aop:aspectj-autoproxy /> 。

For more finer grain control over method executions, you could use Around Advice, too. Also don't forget to enable autoproxy-ing, using @EnableAspectJAutoProxy on a Java config or <aop:aspectj-autoproxy/> in XML configurations.

这篇关于在春天哪里可以捕获非休息控制器异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆