API error handling
easy 24 minGood 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?
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
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.
February 1999
RFC 2518 (WebDAV) adds 422, for content that can be read but not processed.
April 2012
RFC 6585 adds 429 Too Many Requests.
March 2016
RFC 7807 defines problem details, a standard JSON shape for errors.
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.
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 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
{ "error": "Something went wrong" }{ "error": { "code": "VALIDATION_ERROR", "message": "Email is invalid", "field": "email", "hint": "Use a format like user@example.com" }}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
| Status | Name | Means | Example |
|---|---|---|---|
| 400 | Bad Request | The request itself is broken | Missing required field email, or JSON that cannot be read |
| 401 | Unauthorized | Not authenticated | Invalid or expired token. The answer must carry WWW-Authenticate |
| 403 | Forbidden | Known, but not allowed | Cannot delete admin users |
| 404 | Not Found | No such resource, or you may not know | Product id not found |
| 409 | Conflict | Clashes with the current state | Email already registered |
| 422 | Unprocessable Content | Readable, but the values are not valid | Price must be positive |
| 429 | Too Many Requests | Slow down | Retry after 60 seconds |
| 500 | Internal Server Error | We failed in an unexpected way | Unexpected error occurred |
| 502 | Bad Gateway | Something behind us gave a bad answer | Payment service answered nonsense |
| 503 | Service Unavailable | We cannot serve now | Under maintenance or overloaded |
| 504 | Gateway Timeout | Something behind us did not answer in time | Payment service too slow |
Choosing the status
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.
{ "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"}| Member | What it is | Note |
|---|---|---|
type | A URI that names the kind of problem | Programs compare this. Absent means about:blank |
title | A short summary of the kind | The same for every occurrence |
status | The HTTP status again | Advisory, and must equal the real one |
detail | What happened this time | For people. Say how to fix it |
instance | A URI for this occurrence | Not just the endpoint's path |
errors, code, traceId | Extensions | Clients must ignore the ones they do not know |
Our own error codes
| Code | Status | When to use |
|---|---|---|
VALIDATION_ERROR | 422 | Field validation failed |
RESOURCE_NOT_FOUND | 404 | The id does not exist |
DUPLICATE_ENTRY | 409 | A unique constraint was violated |
UNAUTHORIZED | 401 | Not authenticated |
FORBIDDEN | 403 | No permission |
RATE_LIMITED | 429 | Too many requests |
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 failure and its trace id
From an exception to an answer
One id, every log line
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?
Exponential backoff with full jitter
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
| Meaning | HTTP | gRPC | GraphQL |
|---|---|---|---|
| Bad input | 400 or 422 | INVALID_ARGUMENT | errors list, with extensions.code |
| Not signed in | 401 | UNAUTHENTICATED | errors list, or 401 for the whole request |
| Not allowed | 403 | PERMISSION_DENIED | errors list, field is null |
| Not found | 404 | NOT_FOUND | null, or a typed result |
| Already exists | 409 | ALREADY_EXISTS | a typed result |
| Too many | 429 | RESOURCE_EXHAUSTED | errors list, or 429 |
| Try later | 503 | UNAVAILABLE | 503 when nothing ran |
Measure
Counting errors
Error rate
Bring an old API to one format
- 1
List
Collect the error shapes in use today, including the gateway's own 404 and 502 pages.
- 2
Define
Write the problem type list with code, status, meaning and how to fix.
- 3
Centralise
One handler per service, one shared library, tests that force every error path.
- 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.