Reputation: 3497
Why does my web app return 200 when an exception is thrown? Even though I get the correct response body for an error.
A sample response would be:
Status Code = 200
Body: { "error": "User does not exist" }
My code is as follows:
@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");
}
Upvotes: 3
Views: 1114
Reputation: 3497
So the problem was not in the controller but in my SimpleUrlAuthenticationSuccessHandler
. When I was forwarding requests to my controller, I was using RequestDispatcher.include()
instead RequestDispatcher.dispatcher()
because I thought it was the solution to an earlier problem I was having.
Upvotes: 1
Reputation: 51945
You should be able to do this by adding the HttpServletResponse
as a method argument 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");
}
Upvotes: 0