【问题标题】:Can a Spring MVC exception handler ONLY support return type of type View?Spring MVC 异常处理程序只能支持 View 类型的返回类型吗?
【发布时间】:2011-07-31 03:37:54
【问题描述】:
@RequestMapping(value = "/testerror", method = RequestMethod.GET)
        public
        @ResponseBody
        ErrorTO testerror(HttpServletRequest request, HttpServletResponse response) {
           throw new RuntimeException("erorrrrrr");
        }

        @ExceptionHandler(RuntimeException.class)
        public @ResponseBody ErrorTO handlePoprocksExceptionAsReponseBody(RuntimeException ex,
               HttpServletRequest request, HttpServletResponse response) {
            response.setStatus(response.SC_BAD_REQUEST);
            return new ErrorTO(ex.getMessage(), -999);
        }

上面的代码不起作用。 StackTrace 看起来像这样:

org.springframework.web.util.NestedServletException: 请求处理失败;嵌套的 例外是 java.lang.RuntimeException: errrrrrr 在 org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656) 在 org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549) 在 javax.servlet.http.HttpServlet.service(HttpServlet.java:734) 在 javax.servlet.http.HttpServlet.service(HttpServlet.java:847)

我查看了 Spring 3 controller exception handler implementation problems ,基于此,异常处理程序似乎只能返回视图。这是真的吗?

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    您必须让 Spring 知道如何通过您的异常处理程序转换返回对象,以便它可以写入 HTTP 响应。 假设“ErrorTO”是一个 JAXB 对象,然后返回的内容类型是 application/xml,您应该在应用程序上下文中创建一个 HandlerExceptionResolver 并配置一个支持 application/xml 内容类型的消息转换器(例如 org.springframework.http.converter.xml .MarshallingHttpMessageConverter)。这是一个例子:

      <bean id="outboundExceptionAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
        <property name="messageConverters">
          <util:list>
            <ref bean="marshallingHttpMessageConverter"/>
          </util:list>
        </property>
      </bean>
    
      <bean id="marshallingHttpMessageConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
        <property name="marshaller" ref="jaxb2Marshaller" />
        <property name="unmarshaller" ref="jaxb2Marshaller" />
      </bean>
    
      <bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="contextPath" value="com.acme" />
      </bean>
    

    【讨论】:

      【解决方案2】:

      原来是一个错误,据说会在 3.1 中修复。

      【讨论】:

        猜你喜欢
        • 2016-10-27
        • 1970-01-01
        • 2019-12-25
        • 1970-01-01
        • 2011-07-02
        • 2018-03-20
        • 1970-01-01
        • 2011-07-20
        • 2014-01-13
        相关资源
        最近更新 更多