Inconsistent API errors are easier to debug when the client captures the complete response, treats the payload as untrusted input, and translates server details into predictable application states. This checklist shows how to handle API error responses in JavaScript and TypeScript with OpenAPI-compatible schemas, safe parsing, useful diagnostics, and contract tests.
Overview
An API error has several layers, and confusing them is a common source of frontend and Node.js bugs. The HTTP status communicates a broad outcome, response headers may contain request or correlation identifiers, and the body can provide validation details, an error code, or a provider-specific message. Your client should preserve all three rather than assuming that every failure is a JSON object with a message property.
A practical baseline is to use an RFC-style problem-details shape for new endpoints. Typical fields include type, title, status, detail, and instance. An API can extend this with fields such as code, errors, or traceId. The exact field names matter less than documenting them consistently in OpenAPI and keeping the client tolerant of unknown additions.
Different status classes should lead to different handling decisions:
| Status or shape | Typical meaning | Client action |
|---|---|---|
| 4xx | The request, credentials, permissions, or selected resource needs attention. | Show an actionable message, correct input, refresh authentication, or stop retrying. |
| 401 | Authentication is missing, expired, or not accepted. | Use the application’s sign-in or token-refresh flow; do not expose raw server details. |
| 403 | The identity is known but not allowed to perform the operation. | Present a permission state and avoid automatically repeating the request. |
| 404 | The route or requested resource was not found. | Distinguish a missing resource from an incorrect URL when possible. |
| 409 or 422 | The request conflicts with current state or fails validation. | Map field errors or conflict instructions back to the relevant UI. |
| 429 | The client is being limited. | Honor available retry guidance, apply bounded backoff, and protect the user from loops. |
| 5xx | The server or an upstream dependency failed. | Offer a retry where the operation is safe, preserve diagnostics, and log the event. |
| Non-JSON or empty body | A proxy, gateway, framework, or server returned another format. | Use the status and text fallback; never let parsing hide the original failure. |
Retryability is not determined by status alone. A POST that creates a record may not be safe to repeat unless the API supports idempotency. Conversely, a temporary network failure can occur before the server confirms whether an operation completed. Make retry policy part of the endpoint contract rather than a universal response interceptor.
Checklist by scenario
When onboarding an endpoint
- Read the OpenAPI response definitions for success, validation, authentication, authorization, conflict, rate-limit, and server-failure cases.
- Confirm the media types. A response may be JSON, plain text, HTML from a gateway, or empty.
- Record whether the operation is safe to retry and whether it accepts an idempotency key.
- Identify the request or correlation header that support and server logs use to locate the event.
- Write a small client adapter that converts provider-specific details into your application’s internal error type.
When implementing fetch
fetch resolves normally for HTTP error statuses, so a successful promise does not mean the request succeeded. Check response.ok or the status before treating the response as data. Also, a response body can usually be consumed only once. Read it once, then parse or preserve the resulting text.
async function readResponseBody(response: Response): Promise<unknown> {
const text = await response.text();
if (!text) return undefined;
const contentType = response.headers.get("content-type") ?? "";
if (contentType.includes("application/json")) {
try {
return JSON.parse(text) as unknown;
} catch {
return text;
}
}
return text;
}
async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {
const response = await fetch(url, init);
const body = await readResponseBody(response);
const requestId = response.headers.get("x-request-id") ??
response.headers.get("traceparent") ?? undefined;
if (!response.ok) {
throw new ApiError(response.status, body, requestId);
}
return body as T;
}
When using Axios
Axios rejects the promise for configured HTTP error statuses and places the response under error.response. Network failures may have no response at all, while setup failures may have neither a response nor a request. Check these branches explicitly and avoid assuming that error.message contains the server payload.
When mapping errors to a UI
Separate technical diagnostics from user-facing copy. A validation error can become field-level messages, a 401 can trigger authentication state, a 403 can become a permission notice, and a 503 can become a temporary-unavailable state. Keep the original status, safe body, endpoint, method, and request ID available to logging, but do not render tokens, stack traces, SQL fragments, or internal URLs.
When writing TypeScript
Values crossing the network boundary should start as unknown, not as a trusted interface. A type guard can identify the fields your application understands while allowing the server to add fields later.
type ProblemDetails = {
type?: string;
title?: string;
status?: number;
detail?: string;
instance?: string;
code?: string;
errors?: Record<string, string[]>;
};
function isProblemDetails(value: unknown): value is ProblemDetails {
return typeof value === "object" && value !== null;
}
class ApiError extends Error {
constructor(
public readonly status: number,
public readonly body: unknown,
public readonly requestId?: string
) {
super("API request failed");
this.name = "ApiError";
}
}
When adding contract tests
Test more than the happy path. Use fixtures for each documented status, malformed JSON, an empty response, a provider-specific payload, and a response with extra fields. Assert that the client preserves the status and request ID, maps known validation fields, and falls back safely when the server changes its content type. Contract tests should fail when an OpenAPI response changes in a way that affects application behavior.
What to double-check
- OpenAPI completeness: Each meaningful failure response has a documented status, content type, schema, and example. If several statuses share a schema, confirm that the client still uses status-specific behavior.
- Problem-details semantics: Treat
detailas diagnostic content unless the API explicitly says it is safe for end users. Use stable error codes for programmatic decisions instead of matching prose. - Validation shape: Decide whether errors are keyed by field name, represented as an array of objects, or attached to a JSON pointer. Normalize that shape in one place.
- Correlation IDs: Capture the documented response header and include it in logs and support workflows. Do not invent a relationship between a client-generated ID and a server trace unless the API defines one.
- Retries: Check method safety, idempotency, backoff limits, rate-limit headers, and cancellation behavior. A retry should not continue after the user navigates away or cancels the operation.
- Redaction: Remove authorization headers, cookies, personal data, and sensitive request fields before logging raw requests or responses.
- Framework defaults: Review interceptors, middleware, proxy behavior, and generated-client settings after upgrades. These can change whether a body is parsed, which statuses reject, or how unknown fields are handled.
Common mistakes
Checking only for thrown errors. With fetch, a 404 or 500 does not automatically reject. Always inspect the response status.
Parsing every response as JSON. Gate parsing by content type, catch malformed JSON, and retain the raw text fallback. Gateway-generated HTML should not replace the useful status and request ID.
Typing caught errors as a known server schema. A caught value may be a network exception, an abort error, a library error, or an unexpected value. Narrow it before reading fields.
Using display text as a business rule. Messages change during server updates and localization. Prefer documented status codes and stable machine-readable error codes.
Returning raw diagnostics to the browser user. Detailed server messages can reveal implementation information or confuse users. Log safely and provide a short, actionable UI message.
Retrying all failures. Repeating invalid input wastes requests, and repeating a non-idempotent write can create duplicates. Make retry decisions endpoint-aware.
Testing only one provider payload. Migrations, gateways, and framework changes often introduce a different error shape. Fixtures should represent the variations your integration can encounter.
When to revisit
Return to this checklist whenever you add an endpoint, introduce a generated client, change authentication, upgrade a framework, replace an API provider, or add a new UI error state. It is also worth revisiting after a production incident: compare the raw response, OpenAPI contract, client normalization, logs, and displayed message to find where information was lost.
Before releasing an API version, run through these practical actions:
- Compare every documented error response with the client’s type guards and fixtures.
- Verify that status, content type, request ID, and safe diagnostic fields survive normalization.
- Exercise a malformed body, an empty body, a network failure, an authentication failure, a validation failure, a rate limit, and a server failure.
- Confirm that retry behavior is bounded, cancellable, and appropriate for the operation.
- Check the UI copy and logging redaction with realistic payloads, including provider-specific and unexpected fields.
A consistent error workflow does not require every service to return identical prose. It requires a documented contract, defensive parsing, stable application-level categories, and enough preserved context to investigate what happened. Keep those pieces aligned as specifications and client libraries evolve, and API failures become diagnosable states rather than mysterious frontend bugs.