Spring-mvc中所有控制器的@ExceptionHandler [英] @ExceptionHandler for all controllers in spring-mvc

查看:184
本文介绍了Spring-mvc中所有控制器的@ExceptionHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下控制器来处理我的代码中的所有异常:

I have wrote following controller to handle all exception in my code:

@Controller
public class ErrorHandlerController {

    @ExceptionHandler(value = Exception.class)
    public String redirectToErrorPage(Model model){
        model.addAttribute("message", "error on server");
        return "errorPage";
    }
}

但看起来下面的异常处理程序只有在异常时才有效抛出 ErrorHandlerController

But looks like following exception handler will work only if exception throws inside ErrorHandlerController

我有很多控制器。请教我如何为所有控制器编写一个ExceptionHandler?

I have a huge count of controllers. Please advice me how to write one ExceptionHandler for all controllers ?

PS

我知道我可以使用继承,但我不确定这是最好的决定。

I understand that I can use inheritance but I don't sure that it is the best decision.

推荐答案

更改将控制器从 @Controller 注释到 @ControllerAdvice <的方式/ em>将使其成为全局异常处理程序

Change the way you annotate your controller from @Controller to @ControllerAdvice that will make it a global exception handler

文档说


默认行为(即如果没有任何选择器使用),
@ControllerAdvice注释类将协助所有已知的控制器。

The default behavior (i.e. if used without any selector), the @ControllerAdvice annotated class will assist all known Controllers.

此外,您必须将方法更改为

Also, you would have to change your method to something like

@ExceptionHandler(value = Exception.class)
public ModelAndView redirectToErrorPage(Exception e) {
    ModelAndView mav = new ModelAndView("errorPage");
    mav.getModelMap().addAttribute("message", "error on server");
    return mav;
}

了解模型参数未解决的原因在使用@ExceptionHandler注释的方法中,查看更深入的部分-mvcrel =nofollow> http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

To understand why the model argument is not resolved in the method's annotated with @ExceptionHandler check out the going deeper part of the http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

这篇关于Spring-mvc中所有控制器的@ExceptionHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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