Error Handling and Not-Found
A version-qualified path through the Next.js App Router: server components, client boundaries, data fetching, caching layers, streaming, error handling, proxy, images, performance, testing and deployment, with the Next.js 15 and 16 behavior changes called out where they matter.
What you will be able to do
#- Build error.tsx and global-error.tsx boundaries with working reset and accessible messages.
- Distinguish expected failures (notFound, redirect) from unexpected errors and handle each correctly.
- Explain error digesting and what production users may see.
Overview
#Error boundaries as files
error.tsx is a client component that catches errors thrown while rendering the segment below it, including errors thrown in server components during that render. It receives the error and a reset function that re-renders the segment:
'use client';
export default function Error({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
return (
<div role="alert">
<h2>Something went wrong</h2>
<button onClick={reset}>Try again</button>
</div>
);
}
Boundaries nest like layouts: the nearest error.tsx catches, and a sibling segment keeps working. global-error.tsx sits at the root, must render its own <html> and <body> because it replaces the root layout when active, and is the last line of defense.
Expected failures are control flow
notFound() throws a signal that renders the nearest not-found.tsx; redirect(path) throws a signal that navigates. Call them for expected conditions: a missing record calls notFound(), not a thrown Error. Production not-found.tsx handles unmatched URLs too. Next.js 15.4 added an experimental global-not-found.tsx (enabled with experimental.globalNotFound: true; still experimental in 16) that renders a complete HTML document for unmatched routes outside any layout, and it supports metadata exports with automatic noindex.
What production users see
In production, unexpected error messages are sanitized: the client receives a generic message plus a digest, a short hash correlating to the server-side stack in your logs, while development shows the real message and stack. Log the error server-side (the boundary's error object includes the digest) and design the UI around the digest, not the message. Expected errors from Server Actions are better returned as values and surfaced with useActionState, with aria-live="polite" so screen readers announce them.
Recovery design
Give every boundary a recovery path: reset for transient failures, a link home for dead ends, and retry with backoff for flaky data sources. An error state without a next action is a dead end users blame on the app.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
app/dashboard/error.tsx exists, app/dashboard/settings/page.tsx throws during render, and app/billing/page.tsx is fine. A user on /billing navigates to /dashboard/settings and the render throws. What renders, and what does reset() do?
Exercise 2Explain
Explain the difference between calling notFound(), throwing an Error, and returning an error value from a Server Action. Give the right use for each.
Reveal the reference answer
reference.textnotFound() is control flow for a legitimate missing resource: it renders the nearest not-found boundary with a 404 status and no error telemetry noise. Throwing an Error signals an unexpected failure: it triggers the nearest error boundary, produces a digest, and belongs to bugs or infrastructure failures, not user-visible states. Returning an error value from a Server Action is for expected, user-correctable failures such as validation errors: the client reads the value with useActionState and renders an inline message while the form stays filled. Mixing them up produces 404s for real bugs, scary error screens for typos, or silent failures for validation.Authored expected output: Three mechanisms with their correct domains.
Choosing the right channel is most of practical error handling.
Exercise 3Implement
Implement: app/posts/[slug]/page.tsx that calls notFound() for a missing post; app/posts/[slug]/error.tsx with reset and an accessible message; and app/not-found.tsx with a link home.
starter.tsx// app/posts/[slug]/page.tsx // TODO: notFound() for missing post // app/posts/[slug]/error.tsx // TODO: client boundary with reset // app/not-found.tsx // TODO: 404 UI with link homeReveal the reference answer
reference.tsx// app/posts/[slug]/page.tsx import { notFound } from 'next/navigation'; export default async function Post({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params; const post = await getPost(slug); if (!post) notFound(); return <article>{post.title}</article>; } // app/posts/[slug]/error.tsx 'use client'; export default function PostError({ reset }: { error: Error & { digest?: string }; reset: () => void }) { return ( <div role="alert"> <h2>This post could not be loaded</h2> <button onClick={reset}>Try again</button> </div> ); } // app/not-found.tsx import Link from 'next/link'; export default function NotFound() { return ( <main> <h1>Page not found</h1> <Link href="/">Back to home</Link> </main> ); }Authored expected output: Missing posts render the 404 UI; render failures render the boundary with a working retry.
role="alert" announces the failure to assistive technology; the digest stays out of user-facing text.
Exercise 4Debug
This global-error.tsx renders but the page is unstyled and React warns about missing tags. Fix it. 'use client' export default function GlobalError({ error, reset }) { return <div role="alert"><h1>App error</h1><button onClick={reset}>Retry</button></div>; }
starter.tsx'use client' export default function GlobalError({ error, reset }) { return <div role="alert"><h1>App error</h1><button onClick={reset}>Retry</button></div>; }Reveal the reference answer
reference.tsxglobal-error.tsx replaces the root layout when active, so it must render the document shell itself: wrap the output in <html lang="en"><body>...</body></html> and import global styles there if the app relies on them. Without the shell the browser renders an invalid partial document, which is the missing-tags warning and the lost styling.Authored expected output: The global error page renders a complete, styled document.
Replacing the root layout is why global-error has a stricter contract than segment error.tsx.
Exercise 5Test
Write a pure function failureChannel(status: 'missing-record' | 'validation' | 'bug') returning the correct mechanism: missing-record gives notFound(), validation gives return-error-value, bug gives throw-error. Assert all three and an unknown status returning 'error'.
starter.tsexport function failureChannel( status: 'missing-record' | 'validation' | 'bug' | string, ): string { // TODO }Reveal the reference answer
reference.tsexport function failureChannel( status: 'missing-record' | 'validation' | 'bug' | string, ): string { if (status === 'missing-record') return 'notFound()'; if (status === 'validation') return 'return-error-value'; if (status === 'bug') return 'throw-error'; return 'error'; } // Three failure classes, three channels; the mapping is the lesson.Authored expected output: All four assertions pass.
The mapping is small, high-value, and easy to encode as a test.
Exercise 6Interview
An interviewer asks: production users report 'something went wrong' with no useful information. How do you build an error reporting path that actually lets you fix bugs? Cover digests, logging, and the user experience.
Reveal the reference answer
reference.textServer side: log every caught error with its stack and the digest the framework generated, plus request context (route, user id if authenticated, timestamp) in your logging pipeline; alert on digest frequency so new bugs page someone. Client side: the error boundary shows a human message, the digest so support can correlate reports, and a reset action; send the digest and a breadcrumb summary to your monitoring tool from the boundary if you use one. UX: distinguish expected states (empty, not-found) from failures so error screens stay rare and trustworthy; never render raw stack traces to users. Verify the path with an injected failure in a staging environment rather than assuming the boundary fires.Authored expected output: Digest-correlated server logging, client reporting with digest, and staged verification.
The question tests operational maturity, not API recall.
Common misconceptions
#- error.tsx can be a server component. It must be a client component because it renders in response to client-side failure and offers reset.
- global-error.tsx wraps the root layout. It replaces it when active, which is why it must render html and body itself.
- Throwing an Error is the right way to handle a missing record. notFound() is the control-flow signal for that case and renders the not-found boundary.
- Production error messages show the real cause. They are sanitized to a generic message plus digest; the stack stays in server logs.
Follow-up practice
#- nextjs-server-actions
- nextjs-testing-debugging
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.