Card 04/ 07
HTTP Status Codes for Errors: 400 vs 401 vs 404 vs 409
A status code is a claim about what happened, and each kind of failure has its own.
An HTTP status code is the three-digit number at the start of every response, and for an error it is a claim about what went wrong. The four codes below cover most failures in a typical API, and each one should be triggered by an exception that means the same thing.
All four are 4xx codes, which means the problem lies with the request rather than with the server; a failure inside the server is a 500. The table puts them side by side, with an exception that fits each.
| What happened | Status | Exception example |
|---|---|---|
| The resource does not exist | 404 Not Found | RideNotFoundException |
| The request is malformed or fails validation | 400 Bad Request | MethodArgumentNotValidException (built in) |
| The caller is not authenticated | 401 Unauthorized | Spring Security's AuthenticationException family |
| The resource exists and conflicts with the request | 409 Conflict | DuplicateRideException |
The decision rule. 404 means the lookup failed. 400 means the request was never valid to begin with. 401 means nobody has proved who they are. 409 means the request was valid but collided with something that already exists.
A caller reading the status code alone should be able to tell which of these happened. That is what lets a client retry after a 409, ask the user to fix a form after a 400, and show "not found" after a 404, without parsing a message.
← → move through sections and cards