Http status code for exceptions

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 excluding "500" 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());
}
+4
source share
4 answers

This is not a recommended way to handle exceptions, you should use a controller tip, check the link

The status code is determined by the specific scenario, 500 means that the internal server error that I will use for the problem that it causes is not indicated, for 409 it looks like a conflict on the target resource

- . ,

, , , ,

0

. :

https://httpstatuses.com/

  • 1 ××

  • 2 ××

  • 3 ××

  • 4 × × * 400 - * 401 ... * 405 ...

  • 5 ×× * 500 * 501 * 502 Bad Gateway...

, (200, 400, 500 ..) . "" , "".

:

  • "" (, /), 4xx.

  • - (, ), 5xx.

"" HTTP RFC 7231:

https://tools.ietf.org/html/rfc7231

+4

, . , . , - , 500.

, .

, 409 , :

- . , .

400- , .

, , . Exception, , , .

+1

5.XX , 4.XXX .
:

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

, , (, ) (, DB ).

4.XXX 5.XXX, ClientErrorException ServerErrorException.

, , :

try {
    studioService.createStudio(studioDto);
    response.setMessage("The studio was create");
    response.setStatusCode(HttpServletResponse.SC_CREATED);
} 
 catch (ClientErrorException e) {
    response.setStatusCode(409);
}
catch (ServerErrorException e) {
    response.setStatusCode(500);
}

.
:

try {
    studioService.createStudio(studioDto);
    response.setMessage("The studio was create");
    response.setStatusCode(HttpServletResponse.SC_CREATED);

} 
 catch (MyRestException e) {
    response.setStatusCode(e.getStatusCode());
}

These custom exceptions can be thrown directly from your code when an error is detected in a client request ( 4.XXX).
Thus, you can consider all other exceptions related to server processing ( 5.XXX).
A Spring exception handler can easily accomplish this task.

+1
source

Source: https://habr.com/ru/post/1691853/


All Articles