写入响应时,Spring-MVC异常处理程序返回OK

时间:2013-08-12 12:54:14

标签: spring spring-mvc

我正在使用spring-webmvc:3.2.3.RELEASE(及其相关的依赖项)。

我有这个控制器:

@Controller
@RequestMapping("/home")
public class HomeController {

@Autowired
MappingJacksonHttpMessageConverter messageConverter;

@RequestMapping(method = RequestMethod.GET)
public String get() {
 throw new RuntimeException("XXXXXX");
}

@ExceptionHandler(value = java.lang.RuntimeException.class)
@ResponseStatus(HttpStatus.CONFLICT)
public ModelAndView runtimeExceptionAndView(ServletWebRequest webRequest) throws Exception {
    ModelAndView retVal = handleResponseBody("AASASAS", webRequest);
    return retVal;
}

@SuppressWarnings({ "resource", "rawtypes", "unchecked" })
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest) throws ServletException, IOException {
    ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(webRequest.getResponse());
    messageConverter.write(body, MediaType.APPLICATION_JSON, outputMessage);
    return new ModelAndView();
}
}

因为“/ home”方法抛出正在使用@ExceptionHandler处理的RuntimeException,当调用get()方法时,我希望得到HttpStatus.CONFLICT,但相反,我得到的是HttpStatus.OK 。 有人可以告诉我我该怎么做以获得响应状态 带注释的异常处理程序?

2 个答案:

答案 0 :(得分:4)

原因是因为您显式写入输出流,而不是让框架处理它。标题必须在写入正文内容之前进行,如果您明确处理写入输出流,则还必须自己编写标题。

要让框架处理整个流程,您可以改为:

@ExceptionHandler(value = java.lang.RuntimeException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public TypeToBeMarshalled runtimeExceptionAndView(ServletWebRequest webRequest) throws Exception {
    return typeToBeMarshalled;
}

答案 1 :(得分:2)

像这样修改ExceptionHandler方法

@ExceptionHandler(value = java.lang.RuntimeException.class)
public ModelAndView runtimeExceptionAndView(ServletWebRequest webRequest, HttpServletResponse response) throws Exception {
    response.setStatus(HttpStatus.CONFLICT.value());
    ModelAndView retVal = handleResponseBody("AASASAS", webRequest);
    return retVal;
}

如果你想通过json结果处理异常,我建议使用@ResponseBody和Automatic Json返回。

@ExceptionHandler(value = java.lang.RuntimeException.class)
@ResponseBody
public Object runtimeExceptionAndView(ServletWebRequest webRequest, HttpServletResponse response) throws Exception {
    response.setStatus(HttpStatus.CONFLICT.value());
    return new JsonResult();
}