【问题标题】:Spring MVC returning wrong Http Status CodeSpring MVC 返回错误的 Http 状态码
【发布时间】:2014-10-23 23:30:40
【问题描述】:

为什么我的网络应用在抛出异常时返回 200?即使我得到了正确的错误响应正文。

一个示例响应是:

Status Code = 200
Body: { "error": "User does not exist" }

我的代码如下:

@RequestMapping(method = RequestMethod.PUT, value = "/{userId}")
@ResponseStatus(HttpStatus.OK)
public void updateUser(@PathVariable("userId") String userId,
        @RequestBody(required = false) Map<String, String> fields)
        throws UserNotFoundException {
    // code that leads to the exception being thrown
}

@ExceptionHandler(UserNotFoundException.class)
@ResponseBody
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorDto userNotFound() {
    return new ErrorDto("User does not exist");
}

【问题讨论】:

    标签: java spring exception-handling


    【解决方案1】:

    所以问题不在于控制器,而在于我的SimpleUrlAuthenticationSuccessHandler。当我将请求转发到我的控制器时,我使用的是 RequestDispatcher.include() 而不是 RequestDispatcher.dispatcher(),因为我认为这是我之前遇到的问题的解决方案。

    【讨论】:

      【解决方案2】:

      您应该可以通过添加HttpServletResponse 作为方法参数并在此处设置响应代码来做到这一点:

      @ExceptionHandler(UserNotFoundException.class)
      @ResponseBody
      public ErrorDto userNotFound(HttpServletResponse response) {
          response.setStatus(HttpServletResponse.SC_NOT_FOUND);
          return new ErrorDto("User does not exist");
      }
      

      【讨论】:

      • 奇怪 - 我昨天在我自己的项目中使用它,它正在正确设置状态。
      猜你喜欢
      • 2017-03-30
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 2021-09-24
      • 2017-12-20
      相关资源
      最近更新 更多