Card 04/ 07

ComparisonDifficulty: Intermediate1 min

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.

Common failures and the status that fits each
What happenedStatusException example
The resource does not exist404 Not FoundRideNotFoundException
The request is malformed or fails validation400 Bad RequestMethodArgumentNotValidException (built in)
The caller is not authenticated401 UnauthorizedSpring Security's AuthenticationException family
The resource exists and conflicts with the request409 ConflictDuplicateRideException

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.