0
0
NextJSframework~15 mins

Error handling with error.tsx in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Error handling with error.tsx in Next.js
📖 Scenario: You are building a Next.js app that shows a list of products. Sometimes, the data fetching might fail or the page might encounter an error. You want to create a simple error page to show a friendly message when something goes wrong.
🎯 Goal: Create an error.tsx file in the app directory that displays a user-friendly error message. This error page should catch errors and show a heading and a paragraph explaining that something went wrong.
📋 What You'll Learn
Create an error.tsx file exporting a React component named Error.
The Error component should accept a prop called error of type Error.
Display a heading with the text Something went wrong!.
Display the error message inside a paragraph.
Export the Error component as default.
💡 Why This Matters
🌍 Real World
Custom error pages improve user experience by showing friendly messages when something goes wrong in your web app.
💼 Career
Knowing how to handle errors gracefully is important for frontend and full-stack developers working with Next.js or React frameworks.
Progress0 / 4 steps
1
Create the error component file
Create a file named error.tsx inside the app directory. Inside it, write a React functional component named Error that accepts a prop called error of type Error.
NextJS
Need a hint?

Start by defining an interface for the props with error: Error. Then create a function named Error that takes these props.

2
Add a heading to the error component
Inside the Error component, add a <h1> element with the text Something went wrong! to inform users that an error occurred.
NextJS
Need a hint?

Replace the null return with a JSX <h1> element containing the exact text.

3
Display the error message
Below the <h1>, add a <p> element that displays the error message using {error.message}.
NextJS
Need a hint?

Use curly braces inside JSX to insert the error.message value inside a paragraph.

4
Export the error component as default
Make sure the Error component is exported as the default export from error.tsx so Next.js can use it automatically.
NextJS
Need a hint?

The component should already be exported as default. Just verify the export statement is present.