Next.js: The React Framework (App Router)Entry 8 of 16
Errors and Not Found
error.tsx catches errors thrown while rendering a segment and shows fallback UI. not-found.tsx renders when notFound() is called or no route matches.
Notes
error.tsxmust be a Client Component. It receiveserrorand areset()function that retries rendering.- It catches errors in its segment's page and children, not in the layout at the same level.
global-error.tsxhandles errors in the root layout. notFound()fromnext/navigationstops rendering and shows the nearestnot-found.tsx.- Expected errors (validation, "item doesn't exist") should be return values or
notFound(), not thrown exceptions.
What / Why / When
- What
Route-level error and 404 boundaries.
- Why
One failing segment doesn't take down the whole page.
- When
Every app needs a root
not-found.tsx; adderror.tsxto segments with risky data.- Use case
A post page that 404s for unknown slugs.
Code compare
// app/posts/[slug]/page.tsximport { notFound } from "next/navigation";export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params; const post = await getPost(slug); if (!post) notFound(); return <h1>{post.title}</h1>;}// app.routes.ts{ path: 'not-found', loadComponent: () => import('./not-found.component').then((m) => m.NotFoundComponent) },{ path: '**', redirectTo: 'not-found' },Differences and gotchas
- Next.js error boundaries are per segment with built-in retry. Angular has one global
ErrorHandler; per-section error UI is done with resource state (post.error()) and@if. - With SSR, set the 404 status in Angular with
RESPONSE_INITor astatuson the server route so crawlers see a real 404.
Quick reference
| Next.js | Angular |
|---|---|
error.tsx + reset() | ErrorHandler; resource.error() + resource.reload() |
not-found.tsx | ** wildcard route |
notFound() | router.navigate(['/not-found']) |
global-error.tsx | ErrorHandler |