Spring MVC returning invalid Http status code

Why is my web app returning 200 when an exception is thrown? Even if I get the correct response body for the error.

A sample response would be:

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

      

My code looks like this:

@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");
}

      

+3


source to share


2 answers


So, the problem was not with the controller, but mine SimpleUrlAuthenticationSuccessHandler

. When I was sending requests to my controller, I used RequestDispatcher.include()

instead RequestDispatcher.dispatcher()

because I thought it was a solution to a previous problem I ran into.



+1


source


You should do this by adding HttpServletResponse

as an argument to the method and setting the response code there:



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

      

0


source







All Articles