AlgoViz

API error handling

easy 24 min

Good error handling tells the caller what went wrong, why, and what to do next, in one format for the whole API.

Video lesson · Chapter 1 of 6

What can the caller change?

0:00 / 3:54

API errors in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Every API call can fail: the input is wrong, the caller is not allowed, the thing is gone, or a machine broke. API error handling is the part of the design that says what the caller receives in each of those cases.

An error answer has two readers. A program needs a status code and a fixed error code so it can decide: fix, log in, wait or give up. A person needs a sentence that says what happened and what to do. Our own team is a third reader, and gets the details in the logs, linked by an id.

Why it exists

An answer such as *something went wrong* costs time for everybody. The user cannot fix the form, the client cannot know whether trying again is safe, and support cannot find the request. A good error turns a dead end into a next step.

The opposite mistake is to say too much. A stack trace or a database message in the answer tells strangers how the system is built. So the design goal is: useful outside, complete inside, the same shape everywhere.

A short history

  1. May 1996

    RFC 1945 (HTTP/1.0) sets the five classes of status codes: 4xx for the caller's mistakes, 5xx for the server's.

  2. February 1999

    RFC 2518 (WebDAV) adds 422, for content that can be read but not processed.

  3. April 2012

    RFC 6585 adds 429 Too Many Requests.

  4. March 2016

    RFC 7807 defines problem details, a standard JSON shape for errors.

  5. July 2023

    RFC 9457 replaces RFC 7807. It adds a shared registry of problem types and advice on reporting several problems at once.

Words to know

Status code
Three digits in the HTTP answer. 4xx means the request must change, 5xx means the server failed.
Error code
A short fixed name such as DUPLICATE_ENTRY that programs compare.
Problem details
The standard JSON error shape of RFC 9457.
Field error
One problem with one input, with a pointer to it.
Trace id
An id for one request, in the answer and in every log line about it.
Transient error
One that may disappear by itself, such as a brief overload.
Retry-After
A header that says how long to wait before trying again.
Error leak
An answer that shows internal details to the outside.

How it works

Step through the idea, or press Play.

Step 1 of 3

Sort the failure. Whose problem is it: the request, the rules, or our system?

Understand it

Start here

Homework that comes back

Imagine homework that comes back with one big red cross. You know it is wrong and nothing else. Now imagine the same page with two circles and two short notes. You fix it in a minute. Errors work the same way.

The marking desk
Name:Sam, class 41) 3 + 4 = 72) 6 + 5 = 123) 8 + 1 = 94) 7 + 6 = 14But what?Only a cross

The same desk always answers in the same way, so Sam learns once how to read it.

The idea

A bad error and a good one

JSON
{ "error": "Something went wrong" }
Unhelpful: no context, no field, no next step.
JSON
{  "error": {    "code": "VALIDATION_ERROR",    "message": "Email is invalid",    "field": "email",    "hint": "Use a format like user@example.com"  }}
Specific and actionable. The next section turns this home-made shape into the standard one.

A good error

  • Says what to change
  • Has a code a program can compare
  • Names the field
  • Carries a trace id
  • Looks the same in every endpoint

A bad error

  • 200 OK with an error inside, in an HTTP API
  • A stack trace or an SQL message
  • A different shape per team
  • One field problem per attempt
  • A sentence that programs must parse

Status codes

Whose problem is it?

The codes an API uses most

StatusNameMeansExample
400Bad RequestThe request itself is brokenMissing required field email, or JSON that cannot be read
401UnauthorizedNot authenticatedInvalid or expired token. The answer must carry WWW-Authenticate
403ForbiddenKnown, but not allowedCannot delete admin users
404Not FoundNo such resource, or you may not knowProduct id not found
409ConflictClashes with the current stateEmail already registered
422Unprocessable ContentReadable, but the values are not validPrice must be positive
429Too Many RequestsSlow downRetry after 60 seconds
500Internal Server ErrorWe failed in an unexpected wayUnexpected error occurred
502Bad GatewaySomething behind us gave a bad answerPayment service answered nonsense
503Service UnavailableWe cannot serve nowUnder maintenance or overloaded
504Gateway TimeoutSomething behind us did not answer in timePayment service too slow
RFC 9110 renamed 422 from Unprocessable Entity to Unprocessable Content. The number is the same.

Choosing the status

The order matters: do not tell a stranger which ids exist.

Format

Problem details, RFC 9457

RFC 9457 is the current standard for a machine-readable error. It replaced RFC 7807 and kept the same members. The content type is application/problem+json.

JSON
{  "type": "https://api.shop.example/errors/validation",  "title": "Validation error",  "status": 422,  "detail": "Two fields need attention.",  "instance": "/orders/attempts/8841",  "code": "VALIDATION_ERROR",  "errors": [    { "pointer": "#/quantity", "code": "INVALID_VALUE", "detail": "Must be between 1 and 100" },    { "pointer": "#/shipping/zip", "code": "INVALID_FORMAT", "detail": "ZIP code must be 5 digits" }  ],  "traceId": "4bf92f3577b34da6a3ce929d0e0e4736",  "timestamp": "2026-01-15T10:30:00Z"}
type, title, status, detail and instance come from the standard. Everything below is our extension, which the standard allows.
MemberWhat it isNote
typeA URI that names the kind of problemPrograms compare this. Absent means about:blank
titleA short summary of the kindThe same for every occurrence
statusThe HTTP status againAdvisory, and must equal the real one
detailWhat happened this timeFor people. Say how to fix it
instanceA URI for this occurrenceNot just the endpoint's path
errors, code, traceIdExtensionsClients must ignore the ones they do not know
No member is required by the standard. Many teams make type, title, status and traceId mandatory for themselves.

Our own error codes

CodeStatusWhen to use
VALIDATION_ERROR422Field validation failed
RESOURCE_NOT_FOUND404The id does not exist
DUPLICATE_ENTRY409A unique constraint was violated
UNAUTHORIZED401Not authenticated
FORBIDDEN403No permission
RATE_LIMITED429Too many requests
Codes are part of the contract. Add new ones freely; never reuse or rename one. See API versioning.

One place

Where errors are turned into answers

Business code should raise its own errors, such as product not found. One handler at the edge of the service turns each into a status and a body. Everything the handler does not know becomes a plain 500.

Details go to the logs, a safe answer goes out

A client calls our system through the gateway. The order service contains the business code and the error handler. The business code calls the database. Failures go to the error handler, which sends full details to the logs and a safe answer back to the gateway and the client.
Pink is the error on its way out. Orange dashes are the full details, which never leave our system.

A failure and its trace id

Take the id from the W3C traceparent header if a trusted gateway set it. Otherwise make a new one: never log a caller's text unchecked.

From an exception to an answer

Both branches end in the same shape.

One id, every log line

One trace id travels from the gateway to the order service and to the payment service. Each of the three writes log lines with that id to one log store, and a support person finds all of them with one search.
The id in the answer is the key to the whole story across services.

Next step

Try again, or change something?

May be tried again

  • 500, 502, 503, 504 when the call is safe to repeat
  • 429, after Retry-After
  • Network timeouts, if the call is idempotent
  • Connection refused: the request never arrived

Do not repeat unchanged

  • 400, 403, 404: the answer will be the same
  • 401: get a new token first, once
  • 409: needs a fresh read or different data
  • 422: fix the input first
  • POST without an idempotency key

What should the client do?

Safe to repeat means idempotent, or carrying an idempotency key. See idempotency.

Exponential backoff with full jitter

waitn=random(0, min⁡(cap, base⋅2 n))base=1 s:;1, 2, 4, 8 s at mostwait_n = \text{random}\left(0,\ \min(cap,\ base \cdot 2^{\,n})\right) \qquad base = 1\text{ s}:; 1,\ 2,\ 4,\ 8\ \text{s at most}
n counts from 0. The limits grow 1, 2, 4, 8 seconds, at most 15 in total, and the random part keeps clients from returning together.

That is the short version. Retries owns backoff, budgets and jitter. Circuit breaker owns the three states: closed is normal, open rejects at once, half-open lets a few test calls through. Timeouts says how long to wait for an answer at all.

Practice

Six rules that age well

  • Never expose internals

    Stack traces, database errors and file paths stay inside.

  • One format

    Every error of every endpoint has the same structure, including the ones the framework makes.

  • Trace ids

    A unique id per request links the answer to the logs.

  • Specific but safe

    Say invalid credentials, not wrong password, so nobody can test which accounts exist.

  • Log on the server

    Full details in the logs without passwords or tokens, a cleaned version to the client.

  • Recovery hints

    Please try again, change this field, or contact support with this id.

Partial failure

When half of it worked

A batch of ten items where one fails is neither a success nor an error. Choose one rule and document it: all or nothing in a transaction, or one result per item with its own status. With per-item results the caller must read the body, so say in the documentation that 200 (or 207) does not mean all ten worked.

The same ideas in other styles

MeaningHTTPgRPCGraphQL
Bad input400 or 422INVALID_ARGUMENTerrors list, with extensions.code
Not signed in401UNAUTHENTICATEDerrors list, or 401 for the whole request
Not allowed403PERMISSION_DENIEDerrors list, field is null
Not found404NOT_FOUNDnull, or a typed result
Already exists409ALREADY_EXISTSa typed result
Too many429RESOURCE_EXHAUSTEDerrors list, or 429
Try later503UNAVAILABLE503 when nothing ran
More on the styles in REST, GraphQL and gRPC.

Measure

Counting errors

Error rate

5xx answersall answers=2,00010,000,000=0.02%\frac{\text{5xx answers}}{\text{all answers}} = \frac{2{,}000}{10{,}000{,}000} = 0.02\%
Against a target of 99.9% success, the allowance is 0.1%, which is 10,000. 2,000 uses a fifth of it. Count 4xx separately: they are usually the callers' mistakes, but a sudden rise often means we broke a contract.

Bring an old API to one format

  1. 1

    List

    Collect the error shapes in use today, including the gateway's own 404 and 502 pages.

  2. 2

    Define

    Write the problem type list with code, status, meaning and how to fix.

  3. 3

    Centralise

    One handler per service, one shared library, tests that force every error path.

  4. 4

    Migrate

    Add the new members next to the old ones, then remove the old in a new version.

Summary

The whole topic in one minute.

Answer errors with the right status, a stable code, a readable sentence, all field problems at once and a trace id, in one shape for the whole API. RFC 9457 problem details is that shape.

Map known failures in one place, turn everything unknown into a plain 500, and keep the full details in the logs. Tell the caller whether trying again makes sense: 4xx means change something, and most 5xx and 429 mean wait.

  • What, why and how to fix, in one shape everywhere.
  • 4xx: the request must change. 5xx: we failed.
  • 401 is who are you, 403 is you may not.
  • RFC 9457 problem details is the current standard; no member is required.
  • Return every field problem at once.
  • Details in the logs, a trace id in the answer.
  • Say whether to retry, and when.

Sources