4

我正在使用 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。有人可以告诉我应该怎么做才能从带注释的异常处理程序中获取响应状态吗?

4

2 回答 2

4

原因是您明确写入输出流,而不是让框架处理它。标头必须在正文内容被写入之前,如果您明确处理写入输出流,您也必须自己编写标头。

要让框架处理整个流程,您可以这样做:

@ExceptionHandler(value = java.lang.RuntimeException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public TypeToBeMarshalled runtimeExceptionAndView(ServletWebRequest webRequest) throws Exception {
    return typeToBeMarshalled;
}
于 2013-08-12T13:05:19.790 回答
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 return。

@ExceptionHandler(value = java.lang.RuntimeException.class)
@ResponseBody
public Object runtimeExceptionAndView(ServletWebRequest webRequest, HttpServletResponse response) throws Exception {
    response.setStatus(HttpStatus.CONFLICT.value());
    return new JsonResult();
}
于 2013-08-13T03:14:19.833 回答