【问题标题】:Spring-MVC Exception handler returns OK when writing into responseSpring-MVC 异常处理程序在写入响应时返回 OK
【发布时间】:2013-08-13 19:05:34
【问题描述】:

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

【问题讨论】:

    标签: spring spring-mvc


    【解决方案1】:

    像这样修改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和自动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();
    }
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2016-05-24
        • 2022-07-29
        • 1970-01-01
        • 1970-01-01
        • 2018-03-20
        • 2011-07-20
        • 2018-05-20
        • 2011-10-08
        相关资源
        最近更新 更多