Spring-mvc controller and exception handling

后端 未结 5 1081
夕颜
夕颜 2021-02-09 08:33

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

    @Autowired
    SomeService service;
         


        
相关标签:
5条回答
  • 2021-02-09 09:06

    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
                }
            }
        }
    
    0 讨论(0)
  • 2021-02-09 09:09

    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/

    0 讨论(0)
  • 2021-02-09 09:12

    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.

    0 讨论(0)
  • 2021-02-09 09:18

    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.

    0 讨论(0)
  • 2021-02-09 09:25

    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.

    0 讨论(0)
提交回复
热议问题