@ExceptionHandler for all controllers in spring-mvc
Asked Answered
H

1

4

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.

Hutch answered 23/2, 2015 at 16:5 Comment(0)
C
5

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

Caia answered 23/2, 2015 at 16:9 Comment(3)
In debug I see that I don't walk into controller methodHutch
yes, it will not resolve arguments in the global exception handler, I've made an editCaia
Yes, it works. But I don't understand the reason. Please explain.Hutch

© 2022 - 2024 — McMap. All rights reserved.