Error Handling in Nextjs
Created on: Aug 30, 2024
There are two category of error that can occur in nextjs application: expected errors and uncaught exceptions: In this blog we will discuss about uncaught exception
Uncaught exceptions are unexpected errors that indicate bugs or issues that should not occur during the normal flow of your application. These should be handled by throwing errors, which will then be caught by error boundaries.
Nextjs uses Error Boundaries to handle unexpected error and provide a fallback UI.
Next.js uses error boundaries to handle uncaught exceptions. Error boundaries catch errors in their child components and display a fallback UI instead of the component tree that crashed.
Let's understand with a example. Clone my repo and follow below.
git clone https://github.com/keshav-repo/nextjs.git cd error-handling # checkout commit where we can see error git checkout 54bbc44281e6ae30d03ae0b42e23f53a1e468633 npm install npm run build npm run start
Now we have a product page where we can give product id in the path and product page will come. Try to browse http://localhost:3000/product/1 You will see a page with product description. Let's try to browse a product which does not exist suppose http://localhost:3000/product/100 You will see a page like below.
Let's create a file error.txt
and handle the exception gracefully.
"use client"; export default function ErrorBoundry({ error }: { error: Error }) { return <div>{error.message}</div>; }
Again run the the build and check. You will not see error trace.
You can swittch to master branch and build and check again.
git checkout master npm run build npm run start