Skip to content

No. 29React8 min read2,228 words

Error handling in React: boundaries, async and Next.js

A practical guide to error handling in React 19 and Next.js 16: error boundaries, async and event errors, Server Action errors, fallbacks and error reporting.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways ยท 05

The short version

  1. 01Error boundaries catch errors thrown while rendering. They do not catch errors in event handlers or in async code that runs after render, unless that error is rethrown during render or inside a transition.
  2. 02Place error boundaries around independent sections such as widgets, panels and route segments, so one failure degrades a part of the page instead of blanking the whole screen.
  3. 03In Next.js, model expected errors (validation failures, not-found records) as return values or notFound(), and let uncaught exceptions fall through to error.tsx boundaries.
  4. 04fetch only rejects on network failure. Check res.ok and throw on HTTP errors, or a 500 response will be treated as success.
  5. 05Every fallback should explain the problem in plain language, offer a way to retry or navigate away, and report the error to monitoring with enough context to debug it.
On this page ยท 12

Error handling in React comes down to matching the tool to the kind of error. Errors thrown while rendering are caught by error boundaries. Errors in async code and event handlers are not, so you handle those explicitly with state, a data library or a transition. In Next.js, expected errors become return values or notFound(), and unexpected ones fall through to error.tsx. Put boundaries around independent sections, give every fallback a way to recover, and report everything to monitoring.

Most React apps handle the happy path well and fall apart the moment a request returns a 500. A user hits an edge case and half the screen goes blank, with a console error nobody will ever read. Error handling is unglamorous work that decides whether an app feels solid or fragile, so here are the patterns that hold up in production.

The three kinds of errors, and what catches each

A try/catch around a component call does not help, because React renders declaratively. If a component throws while rendering and nothing catches it, React unmounts the tree and you get the blank page. Plan for three categories:

Kind of errorExampleWhat catches it
Render errorsReading a property of undefined, mapping over nullThe nearest error boundary
Async errorsA failed fetch, a rejected promise in an effectYour own code: state, a data library, or rethrowing during render
Event handler errorsA click handler throwsYour own try/catch, unless the work runs inside startTransition

Mixing these up is the root cause of most "why isn't my error boundary working?" questions. The React docs on error boundaries are explicit that boundaries do not catch errors in event handlers or asynchronous code.

Error boundaries for render errors

Error boundaries are React's built-in mechanism, and in React 19 they still have to be class components. You write one once (or use a small library such as react-error-boundary), then reuse it everywhere. We run into this on almost every React development project, so the pattern is worth knowing by heart.

"use client";
 
import { Component, type ErrorInfo, type ReactNode } from "react";
 
interface Props {
  fallback: (error: Error, reset: () => void) => ReactNode;
  onError?: (error: Error, info: ErrorInfo) => void;
  children: ReactNode;
}
 
interface State {
  error: Error | null;
}
 
export class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };
 
  static getDerivedStateFromError(error: Error): State {
    return { error };
  }
 
  componentDidCatch(error: Error, info: ErrorInfo) {
    this.props.onError?.(error, info);
  }
 
  reset = () => this.setState({ error: null });
 
  render() {
    if (this.state.error) {
      return this.props.fallback(this.state.error, this.reset);
    }
    return this.props.children;
  }
}

In App Router projects, render this boundary from Client Components: its fallback is a function, and functions cannot be passed as props from a Server Component. If you need a boundary inside server-rendered UI, use error.tsx or a wrapper Client Component that defines the fallback itself.

The reset callback matters more than people expect. A fallback with a "Try again" button that clears the error state lets users recover without reloading the page, which is the difference between a hiccup and a lost session.

Place boundaries at meaningful seams

One boundary at the root technically works, but any error anywhere then blanks the screen. Put boundaries around independent sections: a dashboard widget, a comments panel, a sidebar. If comments fail to render, the rest of the page keeps working.

<Layout>
  <ErrorBoundary fallback={(_e, reset) => <WidgetError onRetry={reset} />}>
    <RevenueWidget />
  </ErrorBoundary>
 
  <ErrorBoundary fallback={(_e, reset) => <WidgetError onRetry={reset} />}>
    <ActivityFeed />
  </ErrorBoundary>
</Layout>

This is the UI equivalent of a circuit breaker. A good rule: one boundary per thing a user would describe as a separate part of the page, plus one at the root as a last resort.

Error handling in the Next.js App Router

Next.js builds boundaries into the file system. The Next.js error handling guide splits errors into expected errors and uncaught exceptions, and the distinction is useful well beyond Next.js.

Expected errors are values, not exceptions

A form with invalid input or a record that does not exist is not a bug. Model it as data. For missing records, call notFound(), which renders the nearest not-found.tsx. For Server Actions, return the error as part of the result and render it with useActionState:

// app/settings/actions.ts
"use server";
 
import { z } from "zod";
 
const Schema = z.object({ name: z.string().min(1, "Name is required").max(80) });
 
export type State = { error?: string; ok?: boolean };
 
export async function updateName(_prev: State, formData: FormData): Promise<State> {
  const parsed = Schema.safeParse({ name: formData.get("name") });
  if (!parsed.success) {
    return { error: parsed.error.issues[0]?.message ?? "Invalid input" };
  }
  await saveName(parsed.data.name);
  return { ok: true };
}
"use client";
 
import { useActionState } from "react";
import { updateName, type State } from "./actions";
 
export function NameForm() {
  const [state, formAction, pending] = useActionState<State, FormData>(updateName, {});
  return (
    <form action={formAction}>
      <input name="name" aria-describedby="name-error" />
      {state.error && <p id="name-error" role="alert">{state.error}</p>}
      <button disabled={pending}>Save</button>
    </form>
  );
}

The role="alert" and aria-describedby are not decoration: they make the error audible to screen reader users, one of the habits in our accessibility 80/20 guide.

Uncaught exceptions go to error.tsx

An error.tsx file in a route segment wraps that segment in an error boundary. It must be a Client Component. In Next.js 16.2 it receives unstable_retry, which re-fetches and re-renders the segment, alongside the older reset, which only clears the error state.

// app/dashboard/error.tsx
"use client";
 
import { useEffect } from "react";
 
export default function DashboardError({
  error,
  unstable_retry,
}: {
  error: Error & { digest?: string };
  unstable_retry: () => void;
}) {
  useEffect(() => {
    reportError(error); // send to your monitoring tool
  }, [error]);
 
  return (
    <div role="alert">
      <h2>We could not load your dashboard.</h2>
      <button onClick={() => unstable_retry()}>Try again</button>
    </div>
  );
}

Three details to know:

  • Production hides server error messages. Errors thrown in Server Components reach the client with a generic message and a digest. That is deliberate, to avoid leaking secrets. Log the error on the server and use the digest to match it.
  • Root layout errors need global-error.tsx, which replaces the whole document and must render its own html and body tags.
  • notFound() and redirect() work by throwing. If you wrap them in your own try/catch, rethrow them, or the navigation silently fails. Next.js provides unstable_rethrow for exactly this.

For server-side reporting, the onRequestError hook in instrumentation.ts lets you send every server error to your observability provider in one place. We cover the wider setup in observability basics for web apps.

Async errors and data fetching on the client

If you fetch inside a useEffect and the request fails, no error boundary catches it, because the rejection happens after render. Handle it in state:

type UserState =
  | { status: "loading" }
  | { status: "error"; error: Error }
  | { status: "success"; user: User };
 
function useUser(id: string) {
  const [state, setState] = useState<UserState>({ status: "loading" });
 
  useEffect(() => {
    const controller = new AbortController();
    setState({ status: "loading" });
 
    fetch(`/api/users/${id}`, { signal: controller.signal })
      .then((res) => {
        if (!res.ok) throw new Error(`Request failed: ${res.status}`);
        return res.json() as Promise<User>;
      })
      .then((user) => setState({ status: "success", user }))
      .catch((error: unknown) => {
        if (controller.signal.aborted) return;
        setState({
          status: "error",
          error: error instanceof Error ? error : new Error(String(error)),
        });
      });
 
    return () => controller.abort();
  }, [id]);
 
  return state;
}

Two details do real work. The res.ok check matters because fetch only rejects on network failures; a 404 or 500 resolves normally unless you throw. And aborting on cleanup cancels the request when the component unmounts or the id changes, so a slow, stale response can never overwrite a fresh one.

The discriminated union beats three separate isLoading, error and data flags: you cannot represent "loading and errored at once", and TypeScript narrows it cleanly in JSX. It is one of the places strict TypeScript pays for itself.

Let a data library do the heavy lifting

Writing that hook once is educational. Writing it fifty times is a source of subtle bugs. TanStack Query handles caching, retries and cancellation, and can hand errors back to your boundary so the two patterns compose:

import { useQuery } from "@tanstack/react-query";
 
function useUser(id: string) {
  return useQuery({
    queryKey: ["user", id],
    queryFn: async ({ signal }) => {
      const res = await fetch(`/api/users/${id}`, { signal });
      if (!res.ok) throw new Error(`Request failed: ${res.status}`);
      return (await res.json()) as User;
    },
    retry: 2,
    throwOnError: true,
  });
}

With throwOnError: true, a failed query is rethrown during render and caught by the nearest boundary, so render errors and data errors share the same fallback. In App Router projects, much of this client fetching can move to Server Components, as we describe in data fetching patterns in React Server Components.

Event handler errors and transitions

Errors in click handlers are not caught by boundaries, and usually you want to handle them inline anyway: show a toast, keep the form data, let the user try again.

async function handleExport() {
  try {
    await exportReport();
    toast.success("Export started");
  } catch (error) {
    reportError(error);
    toast.error("We could not start the export. Please try again.");
  }
}

There is one exception worth knowing. In React 19, if the work runs inside startTransition (from useTransition) and throws, the error bubbles to the nearest error boundary. That is handy when a failed action should replace a section with its fallback rather than show a toast.

Server errors deserve real shapes

On the server, do not throw raw strings or leak stack traces. Return a consistent error shape so the client can branch on a code instead of parsing English. It is a core habit of designing REST APIs that last.

// app/api/users/[id]/route.ts
export async function GET(
  _req: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const { id } = await params;
  const user = await findUser(id);
 
  if (!user) {
    return Response.json(
      { error: { code: "USER_NOT_FOUND", message: "User does not exist" } },
      { status: 404 },
    );
  }
  return Response.json({ user });
}

A stable code lets the client distinguish "show a friendly not-found message" from "retry, this was probably transient". Messages change with copy edits; codes are your contract.

Catch what slips through

Some errors escape every boundary and handler. Catch them globally so they at least get reported:

  • React root callbacks. createRoot accepts onUncaughtError, onCaughtError and onRecoverableError options in React 19, which are a single place to report errors in client-rendered apps.
  • Unhandled promise rejections. Listen for the browser's unhandledrejection event to report promises nobody awaited.
  • Server-side. Use onRequestError in Next.js, or your framework's equivalent.

What to show the user

A good fallback does three things:

  1. Explains in plain language what failed: "We could not load your invoices", not "TypeError: Cannot read properties of undefined".
  2. Offers a way out: retry, go back, or contact support.
  3. Reports quietly to monitoring with context, such as the route, user ID and component stack.

Keep fallbacks the same size as the content they replace so the layout does not jump, and never put a raw error message in the UI.

Test your error paths on purpose

Error handling that has never run is error handling that does not work. Fallbacks are rarely seen in development, so they rot: a missing import, a fallback that itself throws, a retry button wired to nothing. We make error paths part of the normal test suite:

  • Unit-test boundaries by rendering a child that throws and asserting the fallback appears and the reporting callback fires.
  • Mock failed requests in component tests: a 500, a 404, a network error and a slow response that times out. Each should produce a distinct, sensible UI.
  • Run an end-to-end test with the API down for your most important flow, such as checkout or sign-up, and confirm the user gets a clear message and keeps their input.
  • Throw from a Server Component in a preview deployment to confirm error.tsx renders, the digest appears in your logs, and the alert reaches whoever is on call.

We cover where these tests sit in a wider plan in a testing strategy that pays off.

A production checklist

  1. A root boundary (global-error.tsx in Next.js) exists and renders a branded page.
  2. Each independent section of complex pages has its own boundary.
  3. Every fetch checks res.ok, and every client request can be aborted.
  4. Server Actions return expected errors as values and never leak exception messages.
  5. Fallbacks explain the problem, offer a retry and keep the layout stable.
  6. Client and server errors reach one monitoring tool, with release and user context.
  7. Someone is alerted when error rates change, not just when a user complains.

Common mistakes

  • One boundary at the root and none anywhere else.
  • Swallowing errors in an empty catch so nobody ever finds out.
  • Forgetting res.ok, so failed requests render as empty data.
  • Throwing for validation errors in Server Actions instead of returning them.
  • Catching redirect() or notFound() in a broad try/catch without rethrowing.
  • Retry buttons that retry nothing, because the failed data is still cached.

The short version

Match the tool to the error: boundaries for render failures, explicit state or a data library for async failures, inline handling or transitions for events, and return values for expected errors. Put boundaries at section seams, give every fallback a retry path, and report everything.

If you want a second pair of eyes on your app's error strategy, or a React codebase that fails gracefully from day one, get in touch.

Handled errors still need to be seen; our roundup of the best error monitoring tools covers where to send them.

FAQ ยท 05 questions

Frequently asked questions

Why is my React error boundary not catching an error?

Most likely the error happens outside rendering. Error boundaries only catch errors thrown while React renders, in lifecycle methods and in constructors below them. Errors in click handlers, timeouts and promise callbacks are not caught unless you store them in state and throw during render, or the update runs inside startTransition, in which case React routes the error to the nearest boundary.

Can I write an error boundary as a function component?

Not with React alone. As of React 19, error boundaries still have to be class components that implement getDerivedStateFromError or componentDidCatch. In practice you write one small class once, use a library such as react-error-boundary, or in Next.js use the error.tsx file convention, which creates the boundary for you.

How do I handle errors in Next.js Server Actions?

Return expected errors, like validation failures, as part of the action's result and display them with useActionState. Reserve thrown errors for unexpected failures, which bubble up to the nearest error.tsx boundary. Never return raw exception messages or stack traces to the client.

Why does my Next.js error page show a generic message in production?

Next.js deliberately hides the message of errors thrown in Server Components in production to avoid leaking sensitive details. The client receives a generic message and a digest value. Log errors on the server and use the digest to find the matching entry in your server logs.

Should I show the error message to users?

Usually not the raw message. Technical messages like 'Request failed: 500' mean nothing to users and can reveal internal details. Show a plain-language explanation and a retry or navigation option, and send the technical details to your error monitoring tool.

Filed underReactFrontend

Related service

React Development Services

Maintainable React interfaces and applications.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1โ€“2 weeks
Pricing
Fixed price per phase
You own
All code and accounts