The beginner course used notFound() for an id that doesn't exist. This lesson
is about what that call must not catch. A lookup can end in three ways:
The lookup…
Means
Where it should go
returns a row
the item exists
the page
returns null
the item doesn't exist
notFound(): a 404 and not-found.jsx
throws
nobody could find out
the error boundary: a 500 and error.jsx
The last two look alike on screen, since neither shows the item, but they mean
opposite things to everyone downstream. A 404 tells a search engine to drop the
page and tells the reader the link is wrong. A 500 tells monitoring that
something is broken and tells the reader to try again later.
Read, predict, run
lib/library.js is a pretend database. findItem returns a row or null, and
for the id outage it throws, as a real database client does when it can't
connect. The item page wraps the lookup in a try/catch:
JSX
export default async function ItemPage({ params }) { const { id } = await params; let row; try { row = await findItem(id); } catch { // "Nothing came back, so the item must be missing." row = null; } if (!row) notFound(); return ( <main> <h1>{row.title}</h1> <Link href="/">All items</Link> </main> );}
The segment has both files: not-found.jsx (No such item) and
error.jsx (The library is unavailable). Before running, predict what
Missing and Outage each show, and which status a real server would
send.
A Missing Record Is an Expected ResultNext.js · 7 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Study Library · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import Link from "next/link";
export default function Page() {
return (
<main>
<h1>A Missing Record Is an Expected Result</h1>
<p>
Follow each link. Missing asks for an id that doesn't exist;
Outage asks while the database is down.
</p>
<nav>
<Link href="/items/routing">Routing</Link>
<Link href="/items/forms">Forms</Link>
<Link href="/items/missing">Missing</Link>
<Link href="/items/outage">Outage</Link>
</nav>
</main>
);
}
body {
font: 16px/1.5 system-ui;
margin: 0;
color: #182b3c;
background: #f4f8fc;
}
header,
main {
max-width: 900px;
margin: auto;
padding: 20px;
}
header {
border-bottom: 1px solid #cbd5e1;
}
a {
color: #075985;
}
button,
input,
textarea,
select {
font: inherit;
padding: 8px;
margin: 4px;
}
button {
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 10px;
border: 1px solid #cbd5e1;
text-align: left;
vertical-align: top;
}
pre,
code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.pass {
color: #166534;
}
.fail,
[role="alert"] {
color: #a01818;
}
section {
margin: 16px 0;
padding: 12px;
background: white;
border-radius: 8px;
}
nav {
display: flex;
gap: 16px;
}
"use client";
import { useEffect } from "react";
export default function ItemError({ error, retry }) {
useEffect(() => {
console.log("Item page failed:", error.message);
}, [error]);
return (
<main>
<h1>The library is unavailable</h1>
<p>This is a problem on our side, not a missing item.</p>
<button onClick={() => retry()}>Try again</button>
</main>
);
}
import Link from "next/link";
export default function Missing() {
return (
<main>
<h1>No such item</h1>
<Link href="/">All items</Link>
</main>
);
}
import { notFound } from "next/navigation";
import Link from "next/link";
import { findItem } from "@/lib/library.js";
export default async function ItemPage({ params }) {
const { id } = await params;
let row;
try {
row = await findItem(id);
} catch {
// "Nothing came back, so the item must be missing."
row = null;
}
if (!row) notFound();
return (
<main>
<h1>{row.title}</h1>
<Link href="/">All items</Link>
</main>
);
}
// A pretend database. Asking for "outage" fails the way a real database does
// when it can't be reached: it throws instead of answering.
const items = [
{ id: "routing", title: "Routing" },
{ id: "forms", title: "Forms" },
];
export async function findItem(id) {
await new Promise((resolve) => setTimeout(resolve, 50));
if (id === "outage") throw new Error("Library database unavailable");
return items.find((item) => item.id === id) ?? null;
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Check your prediction
Both show No such item, and on a real server both answer 404. Trace
Outage: findItem("outage") throws, the catch sets row to null, and
if (!row) notFound() treats the outage exactly like a wrong id. error.jsx
never runs, nothing is logged, and a search engine that crawls the page during
the outage is told it no longer exists.
The failure to avoid
A catch that turns every exception into "missing" makes an outage look like
a wrong link, and hides programming mistakes the same way: a typo inside findItem that throws
a TypeError would also become a 404. Only the explicit
"no row" answer should choose the not-found path.
Exercise
Keep the outage on the error path
Change the item page so that Outage shows The library is unavailable
(and its message reaches the console), while Missing still shows No such
item and Forms still shows its title.
Your working spaceNext.js · 7 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Study Library · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import Link from "next/link";
export default function Page() {
return (
<main>
<h1>A Missing Record Is an Expected Result</h1>
<p>
Follow each link. Missing asks for an id that doesn't exist;
Outage asks while the database is down.
</p>
<nav>
<Link href="/items/routing">Routing</Link>
<Link href="/items/forms">Forms</Link>
<Link href="/items/missing">Missing</Link>
<Link href="/items/outage">Outage</Link>
</nav>
</main>
);
}
body {
font: 16px/1.5 system-ui;
margin: 0;
color: #182b3c;
background: #f4f8fc;
}
header,
main {
max-width: 900px;
margin: auto;
padding: 20px;
}
header {
border-bottom: 1px solid #cbd5e1;
}
a {
color: #075985;
}
button,
input,
textarea,
select {
font: inherit;
padding: 8px;
margin: 4px;
}
button {
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 10px;
border: 1px solid #cbd5e1;
text-align: left;
vertical-align: top;
}
pre,
code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.pass {
color: #166534;
}
.fail,
[role="alert"] {
color: #a01818;
}
section {
margin: 16px 0;
padding: 12px;
background: white;
border-radius: 8px;
}
nav {
display: flex;
gap: 16px;
}
"use client";
import { useEffect } from "react";
export default function ItemError({ error, retry }) {
useEffect(() => {
console.log("Item page failed:", error.message);
}, [error]);
return (
<main>
<h1>The library is unavailable</h1>
<p>This is a problem on our side, not a missing item.</p>
<button onClick={() => retry()}>Try again</button>
</main>
);
}
import Link from "next/link";
export default function Missing() {
return (
<main>
<h1>No such item</h1>
<Link href="/">All items</Link>
</main>
);
}
import { notFound } from "next/navigation";
import Link from "next/link";
import { findItem } from "@/lib/library.js";
export default async function ItemPage({ params }) {
const { id } = await params;
let row;
try {
row = await findItem(id);
} catch {
// "Nothing came back, so the item must be missing."
row = null;
}
if (!row) notFound();
return (
<main>
<h1>{row.title}</h1>
<Link href="/">All items</Link>
</main>
);
}
// A pretend database. Asking for "outage" fails the way a real database does
// when it can't be reached: it throws instead of answering.
const items = [
{ id: "routing", title: "Routing" },
{ id: "forms", title: "Forms" },
];
export async function findItem(id) {
await new Promise((resolve) => setTimeout(resolve, 50));
if (id === "outage") throw new Error("Library database unavailable");
return items.find((item) => item.id === id) ?? null;
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
null is an answer: "there is no such item". An exception is the lack of an
answer. Only the first is the page's business; the second already has a file
that handles it, one level up from the page.
Hint 2: a first step
Comment out the catch block's body and add throw inside it, then visit
Outage. Which file renders now? Once you know, ask whether the
try/catch is doing anything useful at all.
With no catch, the exception from findItem leaves the page, and Next.js
shows the nearest error.jsx, which logs the message and offers Try again.
A null still reaches notFound(). Rethrowing from the catch would work too,
but a catch that only rethrows says nothing. Catch an error in a page only
when you can do something specific with it, such as showing cached data.
Explain it without the code
A reader reports that an item page said No such item yesterday and works
today. Which of the two failures would you suspect, and what in the code would
you look for first? Write one sentence for each.
Going further
notFound() and redirect() work by throwing special errors that Next.js
recognizes. That's one more reason to avoid a broad catch: wrapped around
them, it swallows the navigation as well. The next day's lessons come back to
this.
The preview runs code-playpad's Next.js simulation. On a real server the
status codes above are what the browser receives; Day 7 shows how to check.
Completion is saved in this browser only. It does not measure mastery.