@ExceptionHandler for all controllers in spring-mvc

六眼飞鱼酱① 提交于 2019-12-07 16:29:28

问题


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";
    }
}

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

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

P.S.

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


回答1:


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

the docs say

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;
}

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



来源:https://stackoverflow.com/questions/28677971/exceptionhandler-for-all-controllers-in-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!