9

Would like to ask you a best practice question where a spring-mvc controller is concerned. Please review the code below:

    @Autowired
    SomeService service;

    @RequestMapping (...)
    public @ResponseBody Response createSomething () {

       try {

            serviceResponse = service.doSomething();

            //create a success response and return

       }
       catch (SomeServiceException e) {
             //create an error response and return 
       }

}

Is the error handling to be done at the controller level normal practice? Or should the service class not be throwing exceptions like shown above. Please review and let me know.

5 Answers 5

7

I would say you have three strategies depending on your use case.

There are roughly three strategies: HandlerExceptionResolver, @ExceptionHandler and handling exceptions internally within action.

The use cases for these are: common exception handler for whole application, whole controller, specific action accordingly.

Sign up to request clarification or add additional context in comments.

2 Comments

all these handlers are associated with Spring MVC only right ? I mean can I handle any unexpected exception from from Filter or outside the Controller scope ? Because as per doc it says Spring HandlerExceptionResolver implementations deal with unexpected exceptions that occur during controller execution i.e. during Controller Execution
I am using Spring boot with Spring cloud, where intelligent routing takes place. hence no Spring MVC involved. What could be the best way to handle global level exception ? AOP based solution ?
2

I would say best practice would be to use @ExceptionHandler. As the downside to handling the exception in the controller method is that it makes the code less readable and might be repeated across many controller methods.

I would recommend having a base class for your controllers with the @ExceptionHandler defined. This way it can be used for many different controllers, without any code duplication. This would be more readable than the exception resolver approach, but could be used in conjunction.

Comments

1

Service class can/should throw exception.. You can handle those exception in controller for logging purpose..also you can show appropriate error pages on the basis of exception caught on controller..but that will be tedious.. better try spring exception handling..http://www.mkyong.com/spring-mvc/spring-mvc-exception-handling-example/

2 Comments

Rajesh : I am not returning a view from this controller. I am returning a json/ResponseBody, hence I do not have a error page to display. However, I like your suggestion of using @ExceptionHandler instead of doing try and catch blocks. Will that work? Thank you and appreciate your response.
Khush..either u can catch exception in controller and send appropriate error msg as json result and show that accordingly on the screen..this is done in some minor case..but also introduce this exception handler and in case of ajax u will get errorpage.html as ajax response..you can then update this page on a div or iframe on screen..if u like the answer vote it so that i can get some points :)
0

Define bean in bean definition file for Handler class. when any exception is thrown in a program ,resolveException method is called.

  public class Handler
        implements HandlerExceptionResolver
    {

        public Handler()
        {
        }

        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        {
            if(ex instanceof ErrorType1Exception))
            {
                 ModelAndView test = new ModelAndView("errorpage1jsppage");
return test;
            } else
            if(ex instanceof ErrorType2Exception))
            {
                 ModelAndView test1 = new ModelAndView("errorpage2jsppage");
return test1
            }
        }
    }

Comments

0

A good practice with exception handling is to throw early and catch late. In your case, that would mean catching the error at the controller instead of the service. The advantage here is that you can code different controllers based on the client request (SOAP/REST/JSON...), to handle the exceptions differently. But if that logic is in the service, you have less flexibility over how to handle the return from the service, in your response to different clients.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.