Course
Error Handling
Next.js Mastery: From Fundamentals to Full-Stack
Unlock the power of Next.js with this comprehensive course! Starting with the basics, you’ll learn essential skills such as routing, data fetching, and styling. Progress through practical projects, including building your own React Notes app, to gain hands-on experience. Dive into the source code to understand the inner workings and core principles of Next.js. Perfect for developers with a basic knowledge of React and Node.js, this course ensures you’ll be ready to create high-performance full-stack applications efficiently. Join us and master Next.js, backed by industry experts and a supportive learning community.
Error Handling
Next, let's discuss error.js, a special file for creating a UI to display when errors occur.
This feature leverages React's ErrorBoundary functionality. Essentially, it wraps
page.js
and its children in an ErrorBoundary.
Here's a demo to illustrate the effect of
error.js
. Create an error.js
file in the dashboard
directory:
// dashboard/error.js'use client';import { useEffect } from 'react';
export default function Error({ error, reset }) { useEffect(() => { console.error(error); }, [error]);
return ( <div className="flex flex-col items-center justify-center mt-40"> <h1 className="text-3xl text-red-500">Something went wrong!</h1> <button className=" px-11 border border-black rounded-md items-center justify-center bg-zinc-300 mt-10" onClick={() => reset()} > Try again </button> </div> );}
To trigger an error, use the following code for
page.js
at the same level:// dashboard/page.js'use client';import React from 'react';
export default async function Page() { const [error, setError] = React.useState(false);
const handleGetError = () => { setError(true); };
return ( <div className="flex flex-col items-center justify-center mt-40"> <div className="text-3xl">Hello, Dashboard!</div> <> {error ? ( Error() ) : ( <button className=" px-11 border border-black rounded-md items-center justify-center bg-zinc-300 mt-10" onClick={handleGetError} > Get Error </button> )} </> </div> );}
Playground
Sometimes errors are temporary and can be resolved with a retry. Next.js provides a reset function to the component exported by
error.js
, allowing recovery from errors. This function triggers a re-render of the content within the error boundary. If successful, it replaces the error display with the re-rendered content.
Refer to this hierarchy diagram:
From the diagram, you'll notice that since Layout and Template are outside the ErrorBoundary, errors in
layout.js
or template.js
cannot be caught by the same-level ErrorBoundary. To catch errors in specific layouts or templates, handle them in the parent component's error.js
.
If you need to capture errors in the root layout, use global-error.js placed in the
app
directory. This file wraps the entire application and replaces the root layout's content when triggered. Therefore, global-error.js must also define <html>
and <body>
tags.Here's an example of global-error.js:
// app/global-error.js'use client'
export default function GlobalError({ error, reset }) { return ( <html> <body> <h2>Something went wrong!</h2> <button onClick={() => reset()}>Try again</button> </body> </html> )}
Note: global-error.js handles errors in the root layout and template, but it is still recommended to write app/error.js
.