【问题标题】:Exception handler for REST controller in springSpring中REST控制器的异常处理程序
【发布时间】:2013-11-08 21:01:40
【问题描述】:

我想处理异常,以便将 URL 信息自动显示给客户端。有没有简单的方法可以做到这一点?

<bean id="outboundExceptionAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
    <!-- what property to set here? -->
</bean>

【问题讨论】:

    标签: spring spring-mvc exception-handling aop


    【解决方案1】:

    你有两个选择:

    Spring Reference 15.9.1 HandlerExceptionResolver

    Spring HandlerExceptionResolvers 缓解意外之痛 当您的请求由控制器处理时发生的异常 与请求相匹配。 HandlerExceptionResolvers 有点像 您可以在 Web 应用程序中定义的异常映射 描述符 web.xml。但是,它们提供了一种更灵活的方式 处理异常。它们提供有关哪个处理程序的信息 抛出异常时执行。此外,程序化 处理异常的方式为您提供了更多响应选项 适当地在请求被转发到另一个 URL 之前(相同的 最终结果与使用 servlet 特定异常映射时一样)。

    HandlerExceptionResolver 有一个方法,包含你需要的一切:

    HandlerExceptionResolver.resolveException(HttpServletRequest request,
                  HttpServletResponse response,
                  Object handler, Exception ex) 
    

    或者,如果您需要针对不同控制器的不同处理程序:Spring Reference Chapter 15.9.2 @ExceptionHandler

    @ExceptionHandler(IOException.class)
    public String handleIOException(IOException ex, HttpServletRequest request) {
       return "every thing you asked for: " + request;
    }
    

    简答题

    【讨论】:

    【解决方案2】:

    我正在做以下技巧:

     @ExceptionHandler(Exception.class)
          public ModelAndView handleMyException(Exception  exception) {
             ModelAndView mv = new ModelAndView("redirect:errorMessage?error="+exception.getMessage());
             return mv;
                  } 
    
      @RequestMapping(value="/errorMessage", method=RequestMethod.GET)
      @Responsebody
      public String handleMyExceptionOnRedirect(@RequestParamter("error") String error) {
         return error;
              } 
    

    完美无瑕。

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 1970-01-01
      • 2022-11-29
      • 2016-02-07
      • 2021-06-27
      • 2011-02-07
      • 2015-05-07
      • 2014-03-18
      • 2017-12-11
      相关资源
      最近更新 更多