gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:54:35 27 4
gpt4 key购买 nike

@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: 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)

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

最佳答案

您必须让 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>

关于java - Spring MVC 异常处理程序是否只能支持 View 类型的返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5572366/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com