Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC returning wrong Http Status Code

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");
}
like image 593
Hank Avatar asked Jun 30 '26 01:06

Hank


1 Answers

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.

like image 159
Hank Avatar answered Jul 02 '26 14:07

Hank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!