Skip to the code

An error screen that can retry

When the database has a bad moment, the tea list at /teas throws while it renders. Give that part of Leaf and Kettle an error screen: app/teas/error.tsx. Next.js wraps the segment's page, and everything below it, in a React error boundary, and when anything inside throws, it shows this file's default export in its place. Among its props are error, whatever was thrown, and retry, a function that fetches and renders the segment again.

The error boundary that shows the file is a Client Component, so the file must be one too: it starts with "use client".

Show an <h2> with We couldn't load the teas. and a Try again button that calls retry().

Never show the error's message: it can hold details visitors mustn't see. In production, an error thrown in a Server Component arrives with a generic message and a digest, a code that matches the error in the server's logs. When error is an Error with a digest, show Reference: followed by it, so a customer can quote it to support. error can be anything a component threw, not only an Error, so check before you read it.

Report each error with trackError(error) from @/lib/errors: once, after the screen renders, and again only when a different error arrives.

// error: an Error with the digest "4093178266"
<h2>We couldn't load the teas.</h2>
<p>Reference: 4093178266</p>
<button>Try again</button>

The app's other files

lib/errors.ts, read-only. Import it as @/lib/errors.

/** Every error sent to the shop's error tracker. A real shop sends them to a tracking service. */
export const tracked: unknown[] = [];
 
/** Sends an error to the tracker. */
export function trackError(error: unknown) {
  tracked.push(error);
}

What the tests check

  1. shows the heading and a Try again button that calls retry
    const retry = spy();
    render(<App error={new Error("Connection refused")} retry={retry} />);
    expect(screen.getByRole("heading", { level: 2, name: "We couldn't load the teas." })).toBeInTheDocument();
    await user.click(screen.getByRole("button", { name: "Try again" }));
    expect(retry).toHaveBeenCalledTimes(1);
    
  2. shows the digest as a reference, and never the message
    const error = Object.assign(new Error("password authentication failed for user shop_admin"), { digest: "4093178266" });
    render(<App error={error} retry={spy()} />);
    expect(screen.getByText("Reference: 4093178266")).toBeInTheDocument();
    expect(screen.queryByText(/shop_admin/)).not.toBeInTheDocument();
    
  3. shows no reference without a digest, or when what was thrown isn't an Error
    render(<App error={new Error("Connection refused")} retry={spy()} />);
    expect(screen.queryByText(/Reference/)).not.toBeInTheDocument();
    expect(screen.queryByText(/Connection refused/)).not.toBeInTheDocument();
    cleanup();
    render(<App error="offline" retry={spy()} />);
    expect(screen.getByRole("heading", { name: "We couldn't load the teas." })).toBeInTheDocument();
    expect(screen.queryByText(/Reference/)).not.toBeInTheDocument();
    cleanup();
    render(<App error={null} retry={spy()} />);
    expect(screen.getByRole("button", { name: "Try again" })).toBeInTheDocument();
    
  4. reports each error to the tracker once
    const first = new Error("Connection refused");
    const { rerender } = render(<App error={first} retry={spy()} />);
    expect(tracked).toEqual([first]);
    rerender(<App error={first} retry={spy()} />);
    expect(tracked).toEqual([first]);
    const second = new Error("Timed out");
    rerender(<App error={second} retry={spy()} />);
    expect(tracked.length).toBe(2);
    expect(tracked[1]).toBe(second);
    
  5. puts the page back when retry works, as Next.js's boundary does
    let databaseUp = false;
    function TeaList() {
      if (!databaseUp) throw new Error("Connection refused");
      return <p>Green tea</p>;
    }
    // A small stand-in for the boundary Next.js puts around the segment.
    class TeasBoundary extends React.Component {
      state = { thrown: null };
      static getDerivedStateFromError(error) {
        return { thrown: { error } };
      }
      render() {
        if (!this.state.thrown) return this.props.children;
        const retry = () => {
          databaseUp = true;
          this.setState({ thrown: null });
        };
        return <App error={this.state.thrown.error} retry={retry} />;
      }
    }
    render(<TeasBoundary><TeaList /></TeasBoundary>);
    expect(screen.getByRole("heading", { name: "We couldn't load the teas." })).toBeInTheDocument();
    await user.click(screen.getByRole("button", { name: "Try again" }));
    expect(screen.getByText("Green tea")).toBeInTheDocument();
    expect(screen.queryByRole("heading", { name: "We couldn't load the teas." })).not.toBeInTheDocument();
    
  6. is a Client Component, as error files must be
    await renderServer(<App error={new Error("Connection refused")} retry={spy()} />);
    expect(screen.getByRole("heading", { name: "We couldn't load the teas." })).toBeInTheDocument();
    expect(tracked.length).toBe(1);
    

Learn more

app/teas/error.tsxSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).