Announcement Announcement Module
Collapse
No announcement yet.
How to handle Unhandled exceptions in all controller classes with single controller? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to handle Unhandled exceptions in all controller classes with single controller?

    At present I am able to handle excetions at controller level.. I have added this method in all controller classes to handle the exceptions... It is working fine...

    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception e, HttpServletRequest r) {
    String message = e.getMessage();
    ModelAndView mv=new ModelAndView("exceptionPage", "message", message);
    return mv;
    }


    But my question here is can we write a common controller which will handle all the exceptions?, So that I can avoid duplication of exception handling code... I tried this code but seems to be DispatcherServlet is looking the @ExceptionHandler(Throwable.class) annotation with in same controller class..


    @Controller
    public class ExceptionController {

    @ExceptionHandler(Throwable.class)
    public ModelAndView handleException(Throwable e, HttpServletRequest r) {
    String message = e.getMessage();
    ModelAndView mv=new ModelAndView("exceptionPage", "message", message);
    return mv;
    }

    }

    Thanks in advance..

  • #2
    Please use [ code][/code ] tags when posting code, that way it remains readable.

    But my question here is can we write a common controller which will handle all the exceptions?
    You cannot.. The @ExceptionHandler is only visible to the current controller... If you want general exception handling implement your own HandlerExceptionResolver. I suggest a read of the exception handling section in the reference guide.

    Comment


    • #3
      Hi chakinam,

      I suggest put @ExceptionHandler code in some base controller and extend this base controller in all controllers. catch the unhandled exception in every try catch block,

      Comment

      Working...
      X