真实系统不会永远成功。
Next.js 把很多“故障预案”做成了文件约定。
#1. error.tsx —— 某个区域炸了,先把这一层兜住
// app/products/error.tsx
'use client';
export default function Error({
error,
reset,
}: {
error: Error;
reset: () => void;
}) {
return (
<div>
<p>商品区加载失败:{error.message}</p>
<button onClick={() => reset()}>重试</button>
</div>
);
}注意:error.tsx 本身要是 Client Component,因为它要处理交互式恢复。
#2. not-found.tsx —— 店铺号不存在
// app/products/not-found.tsx
export default function NotFound() {
return <h1>你访问的商品不存在</h1>;
}配合页面里主动触发:
import { notFound } from 'next/navigation';
export default async function ProductPage({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const product = null;
if (!product) notFound();
return <div>{slug}</div>;
}