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
fetchonly 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 (
HttpErrorwithstatus,code).
Data layer
- TanStack Query / SWR:
errorstate, automatic retries (configureretryto skip 4xx),onErrorcallbacks, globalQueryCache({ 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. Usereact-error-boundarywithresetKeysorQueryErrorResetBoundary. - Router: route
ErrorBoundaryin React Router,error.tsxin 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";23export class HttpError extends Error {4 constructor(public status: number, message: string, public details?: unknown) {5 super(message);6 }7}89export 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}2223export const queryClient = new QueryClient({24 queryCache: new QueryCache({ onError: (e) => console.error("[query]", e) }), // send to monitoring25 defaultOptions: {26 queries: { retry: (count, e) => !(e instanceof HttpError && e.status >= 400 && e.status < 500) && count < 2 },27 },28});2930export 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.