简体   繁体   中英

Spring-mvc controller and exception handling

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.

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.

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.

服务类可以/应该抛出异常..您可以在控制器中处理这些异常以进行日志记录。因此,您可以根据控制器上捕获的异常显示相应的错误页面。但这将是乏味的..更好的尝试弹簧异常处理..http://www.mkyong.com/spring-mvc/spring-mvc-exception-handling-example/

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
            }
        }
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM