java Spring-mvc 控制器和异常处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13487672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:57:10  来源:igfitidea点击:

Spring-mvc controller and exception handling

javaspringspring-mvc

提问by Khush

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

想问你一个关于 spring-mvc 控制器的最佳实践问题。请查看以下代码:

    @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.

在控制器级别进行错误处理是正常做法吗?或者服务类不应该抛出如上所示的异常。请查看并告诉我。

采纳答案by bmichalik

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

我会说根据您的用例,您有三种策略。

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

大致有 3 种策略:HandlerExceptionResolver、@ExceptionHandler和 action 内部处理异常。

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

这些用例是:整个应用程序的通用异常处理程序、整个控制器、相应的特定操作。

回答by Solubris

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.

我会说最佳实践是使用@ExceptionHandler。在控制器方法中处理异常的缺点是它降低了代码的可读性,并且可能会在许多控制器方法中重复。

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.

我建议为您的控制器定义一个基类,并定义了 @ExceptionHandler。通过这种方式,它可以用于许多不同的控制器,而无需任何代码重复。这将比异常解析器方法更具可读性,但可以结合使用。

回答by Rajesh

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/

服务类可以/应该抛出异常..您可以在控制器中处理这些异常以用于记录目的..您也可以根据控制器上捕获的异常显示适当的错误页面..但这会很乏味..最好尝试spring异常处理..http://www.mkyong.com/spring-mvc/spring-mvc-exception-handling-example/

回答by abishkar bhattarai

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

在 Handler 类的 bean 定义文件中定义 bean。当程序中抛出任何异常时,会调用resolveException 方法。

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

回答by Bass

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.

异常处理的一个好习惯是早抛出和晚捕获。在您的情况下,这意味着在控制器而不是服务上捕获错误。这里的优点是您可以根据客户端请求(SOAP/REST/JSON...)编写不同的控制器,以不同的方式处理异常。但是,如果该逻辑存在于服务中,那么在响应不同客户端时,如何处理来自服务的返回的灵活性就会降低。