𝗘𝗿𝗿𝗼𝗿 𝗕𝗼𝘂𝗻𝗱𝗮𝗿𝗶𝗲𝘀 𝗶𝗻 𝗡𝗲𝘅𝘁.𝗷𝘀 𝗔𝗽𝗽 𝗥𝗼𝘂𝘁𝗲𝗿
Most Next.js apps work well when everything goes right. They fail when things go wrong. High quality apps use error boundaries to handle these failures gracefully.
The App Router uses a different model than the Pages Router. It relies on React Error Boundaries. You use error.js files to catch issues at any level of your route.
How it works:
• Errors stay within the nearest error.js boundary. • Errors do not move to a global handler unless you want them to. • You can show different error screens for different parts of your app.
The error.js file rules:
- It must be a Client Component. Use 'use client' at the top.
- It catches errors in that segment and all its children.
- You get a reset function to retry the failed render.
Use the reset function for temporary issues like network drops. Do not use it for permanent errors.
Use global-error.js for the root layout. The standard error.js does not catch errors in the root layout.js. global-error.js is your last resort. It replaces the root layout, so it needs its own and
tags.Managing different error types:
- Use notFound() for missing data. This triggers not-found.js.
- Use throw Error() for unexpected failures. This triggers error.js.
This separation keeps your app clean. A user looking for a missing blog post sees a 404 page. A user facing a database crash sees an error message.
I use this pattern for an AI image generator. The process has many steps like API calls and file uploads. If one step fails, the error boundary shows a specific message. The reset button lets the user try again without losing their prompt.
A good structure looks like this:
• global-error.js: The final safety net. • error.js: Handles root-level errors. • dashboard/error.js: Handles errors inside the dashboard. • auth/error.js: Handles login or session errors.
This approach prevents one small error from breaking your entire website.
