Results 1 to 3 of 3

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

  1. #1
    Join Date
    Jun 2012
    Posts
    4

    Question 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. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,625

    Default

    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.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3
    Join Date
    Jun 2012
    Location
    Bangalore
    Posts
    1

    Default

    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,

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •