开发者

Can a Spring MVC exception handler ONLY support return type of type View?

@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);
        }

The above code did not work. StackTrace looked like this:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.RuntimeException: erorrrrrr at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549) at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)

I looked at Spring 3 controller exception handler implementation problems , and based on that it seems to b开发者_如何学编程e that exception handlers can only return views. Is that true?


You have to let Spring know how to convert the return Object by you exception handler so it can write to HTTP response. Lets say "ErrorTO" is a JAXB object and then returned content type is application/xml you should create a HandlerExceptionResolver in your application context and configure a message converter that support application/xml content type (e.g. org.springframework.http.converter.xml.MarshallingHttpMessageConverter). here is an example:

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


turns out to be a bug and said to be fixed in 3.1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜