Http status code for Exceptions

Carlos Mario :

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());
}
Amer Qarabsa :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=440826&siteId=1