i have a SpringBoot controller, and i want to return the correct http code status for Exceptions. So, my question is: Which http statu code is better for Exception the "500" one or "409" one?
This is my code:
@PostMapping(value = {"", "/"})
public ResponseEntity<Response> create(@RequestBody StudioDto studioDto,
ServletRequest servletRequest, ServletResponse servletResponse) {
Response response = new Response();
try {
studioService.createStudio(studioDto);
response.setMessage("The studio was create");
response.setStatusCode(HttpServletResponse.SC_CREATED);
} catch (Exception e) {
response.setMessage("Op we have a little problem");
response.setErrorMessage(e.getMessage());
//Which one
//this one 5xx
response.setStatusCode(500);
//Or this one 4xx
response.setStatusCode(409);
}
return new ResponseEntity(response, response.getHttpStatus());
}
Todd gave a great link. This is a better way of thinking about it:
https://httpstatuses.com/
1×× Informational
2×× Success
3×× Redirection
4×× Client Error * 400 Bad Request * 401 Unauthorized ... * 405 Method Not Allowed ...
5×× Server Error * 500 Internal Server Error * 501 Not Implemented * 502 Bad Gateway ...
In other words, each major number (200, 400, 500, etc.) is a CATEGORY. You can "refine" the error code by choosing a specific error within the "category".
To your original question:
If the Client request is "bad" (for example, illegal username/password), then return a 4xx.
If the Server somehow fails (for example, you can't read the database), then return a 5xx.
The "official" list of HTTP error codes is RFC 7231:
https://www.rfc-editor.org/rfc/rfc7231
This is not the recommended way to handle exceptions, you should use controller advice , check this link
The status code is defined by the specific scenario , 500 means internal server error which I would use for a problem which it's cause is not specified, for 409 it resembels conflict on the target resource
The request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request
you have many other status code which is suitable in different cases so I would say no specific status code is the right answer, you can check this link for more info
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With