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.tsx must be a Client Component. It receives error and a reset() function that retries rendering.
  • It catches errors in its segment's page and children, not in the layout at the same level. global-error.tsx handles errors in the root layout.
  • notFound() from next/navigation stops rendering and shows the nearest not-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; add error.tsx to segments with risky data.

Use case

A post page that 404s for unknown slugs.

Code compare

Next.js
// 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>;}
Angular
// 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_INIT or a status on the server route so crawlers see a real 404.

Quick reference

Next.jsAngular
error.tsx + reset()ErrorHandler; resource.error() + resource.reload()
not-found.tsx** wildcard route
notFound()router.navigate(['/not-found'])
global-error.tsxErrorHandler