Spring MVC异常处理程序是否只支持View类型的返回类型?

时间:2011-04-06 20:11:41

标签: java spring spring-mvc

@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:erorrrrrr               在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 ,基于此,似乎异常处理程序只能返回视图。这是真的吗?

2 个答案:

答案 0 :(得分:1)

你必须让Spring知道如何通过异常处理程序转换返回Object,以便它可以写入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>

答案 1 :(得分:0)

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