ReactMedium

Error handling in API?

Handle API errors at three levels: in the request layer (check res.ok, parse error bodies, classify network, timeout, 4xx and 5xx errors), in the data layer (retries with backoff for transient failures, but not for 4xx), and in the UI (inline error messages with retry actions, error boundaries for unexpected failures, and toasts for mutations). Log unexpected errors to monitoring.

Request layer

  • fetch only rejects on network failure; throw your own error for !res.ok.
  • Parse the error body to show useful messages (validation errors per field).
  • Use AbortSignal.timeout() for timeouts.
  • Create typed error classes (HttpError with status, code).

Data layer

  • TanStack Query / SWR: error state, automatic retries (configure retry to skip 4xx), onError callbacks, global QueryCache({ onError }) for toasts.
  • Mutations: roll back optimistic updates on failure.
  • Auth errors: on 401, try a token refresh once, then redirect to login.

UI layer

  • Inline: "Couldn't load orders. Retry" next to the failed section.
  • Error boundaries: catch rendering errors and errors thrown by Suspense data (useSuspenseQuery, use()); React 19 Actions also send errors to the nearest boundary. Use react-error-boundary with resetKeys or QueryErrorResetBoundary.
  • Router: route ErrorBoundary in React Router, error.tsx in Next.js.
  • Forms: map server validation errors to fields.

Root-level reporting (React 19)

createRoot(el, { onCaughtError, onUncaughtError, onRecoverableError }) lets you send errors to Sentry or similar.

Do not

Swallow errors silently, show raw stack traces, or retry non-idempotent requests blindly.

Code example

tsx
1import { QueryCache, QueryClient, useQuery } from "@tanstack/react-query";
2
3export class HttpError extends Error {
4 constructor(public status: number, message: string, public details?: unknown) {
5 super(message);
6 }
7}
8
9export async function getJson<T>(url: string, signal?: AbortSignal): Promise<T> {
10 let res: Response;
11 try {
12 res = await fetch(url, { signal: signal ?? AbortSignal.timeout(8000) });
13 } catch (e) {
14 throw new HttpError(0, (e as Error).name === "TimeoutError" ? "Request timed out" : "Network error");
15 }
16 if (!res.ok) {
17 const body = await res.json().catch(() => ({}));
18 throw new HttpError(res.status, body.message ?? `Request failed (${res.status})`, body);
19 }
20 return res.json();
21}
22
23export const queryClient = new QueryClient({
24 queryCache: new QueryCache({ onError: (e) => console.error("[query]", e) }), // send to monitoring
25 defaultOptions: {
26 queries: { retry: (count, e) => !(e instanceof HttpError && e.status >= 400 && e.status < 500) && count < 2 },
27 },
28});
29
30export function Orders() {
31 const { data, error, refetch, isPending } = useQuery({ queryKey: ["orders"], queryFn: ({ signal }) => getJson<{ id: string }[]>("/api/orders", signal) });
32 if (isPending) return <p>Loading…</p>;
33 if (error) return <p role="alert">{error.message} <button onClick={() => refetch()}>Retry</button></p>;
34 return <p>{data.length} orders</p>;
35}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app