Error Handling

guides

Error Handling

API calls fail. Networks drop, servers crash, and requests are malformed. Robust clients handle errors gracefully instead of crashing.

HTTP Status Code Ranges

  • 2xx - success. 200 OK, 201 Created, 202 Accepted, 204 No Content.
  • 3xx - redirection. Follow Location headers when appropriate.
  • 4xx - client error. The request is wrong; do not blindly retry without fixing it.
  • 5xx - server error. Transient; safe to retry with backoff.

Parsing Error Bodies

Most REST APIs return a JSON error object with code, message, and often details or param. Parse these to surface actionable messages to users. Map provider error codes to your application’s error vocabulary.

Retry Strategy

Retry only idempotent operations (GET, PUT, DELETE) on 5xx and 429. For POST, use an idempotency key (Stripe, Adyen) so a retry cannot double-charge. Use exponential backoff with jitter and a maximum retry count.

Best Practices

  • Set timeouts (10-30s) so a hung request does not block forever.
  • Distinguish retryable from non-retryable errors.
  • Log request IDs (X-Request-Id) for support correlation.
  • Surface user-friendly messages, hide raw internals.
  • Circuit-break a failing downstream to avoid cascading failures.

Other languages