Search code examples
javaspring-mvcexceptioncustom-error-pages

@ExceptionHandler for all controllers in spring-mvc


I've written the following controller to handle all exceptions 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.


Solution

  • 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