Practical API Tutorial
How to Test API Error Responses in Your Frontend
Most frontends are built against successful responses and break on the first 401 or 500. Create one mock endpoint per failure, then build a client and UI that handle each one on purpose.
Works on the Free plan. No payment card needed.
What we are building
Nine endpoints, one client, clear UI states
You will create mock endpoints that fail in specific ways, write a typed fetch client that turns every failure into a predictable error, and decide what the interface does for each one. The examples use React and TypeScript, but the client works in any framework.
| Endpoint | Status | Scenario | What the UI does |
|---|---|---|---|
| GET /errors/bad-request | 400 | Malformed request | Generic error message |
| GET /me-signed-out | 401 | Session expired | Send the user to sign in |
| GET /admin/reports | 403 | Signed in, not allowed | Explain the missing permission |
| GET /products/999 | 404 | Record does not exist | Show a not-found state |
| POST /orders-conflict | 409 | Duplicate or stale data | Explain the conflict |
| POST /signup-invalid | 422 | Validation failed | Show messages next to fields |
| GET /search-rate-limited | 429 | Too many requests | Wait for Retry-After, then retry |
| GET /errors/server | 500 | Unexpected server failure | Generic error, no automatic retry |
| GET /errors/unavailable | 503 | Temporarily unavailable | Retry with backoff |
If your plan limits the number of endpoints in a project, start with 401, 404, 422, 429 and 500. They cover the decisions most screens need.
Choose an error format
Use one error body for every failure
Your client is simpler when every error has the same shape. A code for your logic, a message for people, and optional field messages for forms are enough for most apps.
{
"error": {
"code": "validation_failed",
"message": "Some fields need attention.",
"fields": {
"email": "Enter a valid email address."
}
}
}Forge API's own errors, such as an unknown path (404, endpoint_not_found) or a wrong method (405), use the same error.code and error.message fields, so the client below handles them too.
Create the endpoints
Create one endpoint per failure
In your Forge API project, create each endpoint from the table above with its status code and an error body. Each endpoint returns one configured response for its method and path, so every failure needs its own path. Requests do not change it: the same call always fails in the same way, which is what makes these tests repeatable.
The 429 endpoint needs two response headers. Retry-After tells the client how long to wait. Browsers hide that header from JavaScript on cross-origin requests unless the response also lists it in Access-Control-Expose-Headers.
Status code: 429
Response headers:
Retry-After: 30
Access-Control-Expose-Headers: Retry-AfterCheck the endpoint before writing code
Run curl -i against each URL and confirm the status line and headers. See Endpoints for how status codes and response headers are configured.
Write the client
Turn every failure into a typed error
fetch only rejects when no response arrives at all. A 404 or 500 resolves normally with response.ok set to false. The client checks that, reads the body safely (a 204 or a failed proxy may return no JSON), and throws one of two errors:
ApiErrorwhen the server answered with an error status, carrying the status, code, field errors and Retry-After.NetworkErrorwhen there was no response: offline, DNS failure, or a request blocked by CORS.
// src/lib/apiClient.ts
const API_BASE_URL = "https://apis.getforgeapi.com/YOUR_PROJECT_KEY";
type ErrorBody = {
error?: {
code?: string;
message?: string;
fields?: Record<string, string>;
};
};
export class ApiError extends Error {
readonly status: number;
readonly code: string;
readonly fieldErrors: Record<string, string>;
readonly retryAfterSeconds: number | null;
constructor(response: Response, body: ErrorBody | null) {
super(body?.error?.message ?? `Request failed with status ${response.status}`);
this.name = "ApiError";
this.status = response.status;
this.code = body?.error?.code ?? "unknown_error";
this.fieldErrors = body?.error?.fields ?? {};
this.retryAfterSeconds = parseRetryAfter(
response.headers.get("Retry-After"),
);
}
}
/** fetch rejected before any response arrived: offline, DNS, CORS. */
export class NetworkError extends Error {
constructor(cause: unknown) {
super("The request could not reach the server.", { cause });
this.name = "NetworkError";
}
}
function parseRetryAfter(value: string | null): number | null {
if (!value) return null;
const seconds = Number(value);
if (Number.isFinite(seconds)) return Math.max(0, seconds);
// Retry-After can also be an HTTP date.
const date = Date.parse(value);
if (Number.isNaN(date)) return null;
return Math.max(0, Math.ceil((date - Date.now()) / 1000));
}
async function readJson(response: Response): Promise<unknown> {
// 204 responses, and some errors, have no body at all.
const text = await response.text();
if (!text) return null;
try {
return JSON.parse(text);
} catch {
return null;
}
}
export async function apiRequest<T>(
path: string,
init: RequestInit = {},
): Promise<T> {
let response: Response;
try {
response = await fetch(`${API_BASE_URL}${path}`, {
...init,
headers: { Accept: "application/json", ...init.headers },
});
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") {
throw error;
}
throw new NetworkError(error);
}
const body = await readJson(response);
if (!response.ok) {
throw new ApiError(response, body as ErrorBody | null);
}
return body as T;
}Decide the UI
Map each status to one action
Components should not need to know status codes. One function converts any error into an action the interface understands. A 400 or 422 with field messages becomes form errors; anything unknown becomes a generic message.
// src/lib/describeError.ts
import { ApiError, NetworkError } from "./apiClient";
export type ErrorAction =
| { kind: "sign-in" }
| { kind: "forbidden"; message: string }
| { kind: "not-found" }
| { kind: "field-errors"; fields: Record<string, string> }
| { kind: "conflict"; message: string }
| { kind: "retry-later"; seconds: number | null }
| { kind: "offline" }
| { kind: "unexpected"; message: string };
export function describeError(error: unknown): ErrorAction {
if (error instanceof NetworkError) return { kind: "offline" };
if (!(error instanceof ApiError)) {
return { kind: "unexpected", message: "Something went wrong." };
}
switch (error.status) {
case 401:
return { kind: "sign-in" };
case 403:
return { kind: "forbidden", message: error.message };
case 404:
return { kind: "not-found" };
case 409:
return { kind: "conflict", message: error.message };
case 400:
case 422:
return Object.keys(error.fieldErrors).length > 0
? { kind: "field-errors", fields: error.fieldErrors }
: { kind: "unexpected", message: error.message };
case 429:
case 503:
return { kind: "retry-later", seconds: error.retryAfterSeconds };
default:
return { kind: "unexpected", message: error.message };
}
}Retry safely
Retry only what is safe to repeat
Retrying helps with temporary failures: 429, 502, 503, 504 and network errors. It does not help with 400, 401, 404 or 422, and a 500 usually means a bug that will fail again. Each retry waits longer than the last, with a little randomness so many clients do not retry at the same moment. When the server sends Retry-After, that wins. If it asks for a longer wait than the client allows, the client stops retrying and the UI shows the wait time instead.
// src/lib/retry.ts
import { ApiError, NetworkError } from "./apiClient";
const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
function isRetryable(error: unknown) {
if (error instanceof NetworkError) return true;
return error instanceof ApiError && RETRYABLE_STATUSES.has(error.status);
}
function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Retries a request that is safe to repeat, such as a GET.
* Do not wrap POST requests that create data: a retry could create it twice.
*/
export async function withRetry<T>(
request: () => Promise<T>,
{ attempts = 3, baseDelayMs = 500, maxDelayMs = 10_000 } = {},
): Promise<T> {
for (let attempt = 1; ; attempt++) {
try {
return await request();
} catch (error) {
if (attempt >= attempts || !isRetryable(error)) throw error;
const retryAfter =
error instanceof ApiError ? error.retryAfterSeconds : null;
// The server asked for a longer wait than we are willing to block
// the screen for: stop and let the UI show the wait time instead.
if (retryAfter !== null && retryAfter * 1000 > maxDelayMs) throw error;
const backoff = baseDelayMs * 2 ** (attempt - 1);
const jitter = Math.random() * baseDelayMs;
const delay =
retryAfter !== null ? retryAfter * 1000 : backoff + jitter;
await wait(Math.min(delay, maxDelayMs));
}
}
}Do not retry POST requests automatically
A POST that failed with a timeout may still have created the order on the server. Retrying it can create a duplicate. Let the user retry, or use an idempotency key if your API supports one.
Show the states
Render each state in React
Pass a different path to see each state: /products for success, /me-signed-out for 401, /search-rate-limited for 429. Keep the paths in one config file so switching scenarios is a one-line change.
// src/components/ProductsPage.tsx
import { useEffect, useState } from "react";
import { apiRequest } from "../lib/apiClient";
import { describeError, type ErrorAction } from "../lib/describeError";
import { withRetry } from "../lib/retry";
type Product = { id: number; name: string; price: number };
type State =
| { status: "loading" }
| { status: "ready"; products: Product[] }
| { status: "error"; action: ErrorAction };
export function ProductsPage({ path = "/products" }: { path?: string }) {
const [state, setState] = useState<State>({ status: "loading" });
useEffect(() => {
let ignore = false;
setState({ status: "loading" });
withRetry(() => apiRequest<Product[]>(path))
.then((products) => {
if (!ignore) setState({ status: "ready", products });
})
.catch((error: unknown) => {
if (!ignore) setState({ status: "error", action: describeError(error) });
});
return () => {
ignore = true;
};
}, [path]);
if (state.status === "loading") return <p role="status">Loading products…</p>;
if (state.status === "ready") {
return state.products.length === 0 ? (
<p>No products yet.</p>
) : (
<ul>
{state.products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
const { action } = state;
switch (action.kind) {
case "sign-in":
return <a href="/login">Your session has ended. Sign in again.</a>;
case "not-found":
return <p>We could not find these products.</p>;
case "retry-later":
return (
<p role="alert">
Too many requests.{" "}
{action.seconds !== null
? `Try again in ${action.seconds} seconds.`
: "Try again shortly."}
</p>
);
case "offline":
return <p role="alert">You appear to be offline.</p>;
default:
return <p role="alert">Something went wrong. Please try again.</p>;
}
}Validation errors belong next to the fields they describe, linked with aria-describedby so screen readers announce them.
// src/components/SignupForm.tsx
import { useState, type FormEvent } from "react";
import { apiRequest } from "../lib/apiClient";
import { describeError } from "../lib/describeError";
export function SignupForm() {
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [formError, setFormError] = useState("");
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setFieldErrors({});
setFormError("");
const form = new FormData(event.currentTarget);
try {
// Point this at /signup-invalid to see the 422 state.
await apiRequest("/signup-invalid", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: form.get("email") }),
});
} catch (error) {
const action = describeError(error);
if (action.kind === "field-errors") setFieldErrors(action.fields);
else setFormError("We could not create your account. Please try again.");
}
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
type="email"
aria-invalid={Boolean(fieldErrors.email)}
aria-describedby={fieldErrors.email ? "email-error" : undefined}
/>
{fieldErrors.email ? <p id="email-error">{fieldErrors.email}</p> : null}
{formError ? <p role="alert">{formError}</p> : null}
<button type="submit">Create account</button>
</form>
);
}For the full set of loading, empty and error states in React, see How to Use a Mock API in React.
Using Axios
The same idea with Axios
Axios rejects every non-2xx response, so the work moves into a response interceptor. error.response is undefined when no response arrived, which is the Axios equivalent of a network error. Axios lowercases header names, so read retry-after.
// src/lib/axiosClient.ts
import axios, { AxiosError } from "axios";
export const api = axios.create({
baseURL: "https://apis.getforgeapi.com/YOUR_PROJECT_KEY",
timeout: 10_000,
});
export type NormalisedError = {
status: number | null; // null: no response (offline, CORS, timeout)
code: string;
message: string;
fieldErrors: Record<string, string>;
retryAfterSeconds: number | null;
};
api.interceptors.response.use(undefined, (error: unknown) => {
if (!(error instanceof AxiosError)) return Promise.reject(error);
const response = error.response;
const body = response?.data?.error;
const retryAfter = Number(response?.headers["retry-after"]);
const normalised: NormalisedError = {
status: response?.status ?? null,
code: body?.code ?? error.code ?? "unknown_error",
message: body?.message ?? error.message,
fieldErrors: body?.fields ?? {},
retryAfterSeconds: Number.isFinite(retryAfter) ? retryAfter : null,
};
return Promise.reject(normalised);
});Network and CORS
Errors that have no status code
When the request never gets a response, there is no status to check. Your app should still show something useful:
- Offline:use the Offline option in your browser's developer tools to test the
NetworkErrorpath. - CORS: a blocked request also surfaces as a network error, and the real reason only appears in the browser console. Forge API sends
Access-Control-Allow-Origin: *, so a CORS error usually means the request went to the wrong host. - Timeouts: a request that hangs never fails on its own. The slow responses tutorial adds timeouts and cancellation.
The troubleshooting guide explains Forge API's own 404, 405 and missing-header responses.
Automate it
Test the error handling
Because each endpoint always returns the same error, tests against it are stable. This Vitest example checks that the client and describeError agree with the endpoints you created.
// src/lib/apiClient.test.ts (Vitest)
import { describe, expect, it } from "vitest";
import { ApiError, apiRequest } from "./apiClient";
import { describeError } from "./describeError";
describe("API error handling", () => {
it("turns a 422 into field errors", async () => {
const error = await apiRequest("/signup-invalid", { method: "POST" }).catch(
(caught: unknown) => caught,
);
expect(error).toBeInstanceOf(ApiError);
expect(describeError(error)).toEqual({
kind: "field-errors",
fields: { email: "Enter a valid email address." },
});
});
it("reads Retry-After from a 429", async () => {
const error = await apiRequest("/search-rate-limited").catch(
(caught: unknown) => caught,
);
expect(describeError(error)).toEqual({ kind: "retry-later", seconds: 30 });
});
});Know when to use an in-process mock
Every request to a hosted endpoint counts towards your monthly allowance, and a hosted endpoint cannot fail once and then succeed. For fast unit tests that run on every save, or for retry sequences, an in-process mock such as MSW is a better fit. See choosing a mocking approach.
Frequently asked questions
Testing API error responses
How do I make a mock API return a 500 error?
Create an endpoint such as /errors/server, set its status code to 500 and give it a JSON error body. Forge API returns that status and body every time the endpoint is called, so your frontend's error state can be built and tested repeatedly.
Why does response.headers.get("Retry-After") return null in the browser?
Browsers only let JavaScript read a short list of response headers from another origin. Retry-After is not on that list, so the server must also send Access-Control-Expose-Headers: Retry-After. Add both headers to your 429 endpoint.
Should I retry failed POST requests?
Usually not automatically. A POST that timed out may still have succeeded on the server, so retrying it can create a duplicate order or payment. Retry GET requests, and only retry a POST when the API supports idempotency keys.
Can a mock endpoint fail once and then succeed?
Not on its own. A Forge API endpoint returns the same configured response every time. To test a failure followed by a success in an automated test, use an in-process mock such as MSW, or point the test at two different paths.
Do error endpoints work on the Free plan?
Yes. Status codes from 100 to 599 and custom response headers such as Retry-After can be configured on every plan. Every request counts towards your monthly allowance, including requests made by automated tests.
Create your error endpoints
Add 401, 404, 422, 429 and 500 responses to a free Forge API project and test every error state your frontend needs to handle.