Spring MVC返回错误的Http状态代码

时间:2014-10-23 23:30:41

标签: java spring exception-handling

为什么我的网络应用会在抛出异常时返回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");
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您应该可以通过添加HttpServletResponse作为方法参数并在其中设置响应代码来实现此目的:

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