How to Design API Error Handling

A reliable integration defines which failures to retry, explain to the user or escalate to an operator.

Separate errors by source

Validation failure, missing authorisation, rate limiting, timeout and a 500 response are different situations. One generic error hides the action available to the user or system.

Identify who can resolve the problem: user, your code, external provider or administrator. That determines the status, message and retry policy.

API error handling flow from validation through retry and a useful response

Validation and the API contract

Validate required fields, types, lengths and allowed values before the external request. Users receive precise feedback and the integration does not waste rate limits on invalid data.

Validate the response as well. A 200 status does not guarantee the payload has the expected structure or the business operation completed.

  • Do not trust data merely because a TypeScript type exists.
  • Record the API version and expected enums.
  • Handle a missing field without crashing the whole process.
  • Never expose a raw stack trace to the user.

Timeouts, retries and rate limits

Every external request needs a timeout. Without one, a stalled provider can keep a worker or user journey waiting indefinitely.

Retries use backoff, a strict attempt limit and jitter. Respect Retry-After for 429 responses, and protect payments or create operations with idempotency.

SituationTypical response
400 validationDo not retry; identify the field
401/403Fix authorisation rather than retry blindly
429Wait according to provider guidance
Timeout/5xxLimited retry for a safe operation

Logs without leaking secrets

Logs can include request ID, endpoint category, status, duration and safe context. Access tokens, passwords, card data and full personal payloads do not belong there.

A correlation ID that travels through form, server and provider helps trace one journey without searching by personal data.

  • Mask tokens and cookies.
  • Retain logs only as long as needed.
  • Separate user messages from internal diagnostics.
  • Alert on repeated critical failures.

What the user should see

Feedback should say whether data was saved and what to do next. If repetition is unsafe, do not invite another click before checking the status.

For long operations, expose progress and deliver the result asynchronously. Reliability is not the absence of failure; it is predictable behaviour when failure occurs.

Quick answers

Frequently asked questions

Should every 500 response be retried?

No. Retry expected temporary failures only, and only when duplicate outcomes are prevented.

What is an idempotency key?

A stable operation identifier that helps the server avoid creating a second result after a repeated request.

Can full API responses be logged?

Only after data review and secret masking; complete payloads are often unnecessary and risky.