Error handling using "error.tsx" file
An error file defines an error UI boundary for a route segment. It is useful for catching unexpected errors and displaying a fallback UI.
import ReloadButton from "@/components/ReloadButton";
const Profile = () => {
const number = Math.random() * 100;
if (number > 50)
throw new Error(
`Error occored because the number is ${number} which is greater than 50`
);
return (
<>
<h2>This is profile page which is in router group (user)</h2>
<ReloadButton/>
</>
);
};
export default Profile;
To handle the above error, let's create an error.tsx file at the same route level.
"use client";
import { useRouter } from "next/navigation";
import { startTransition } from "react";
export default function ErrorPage({
error,
reset,
}: {
error: Error;
reset: () => void;
}) {
const router = useRouter();
const reload = () => {
startTransition(() => {
router.refresh();
reset();
});
};
return (
<>
<main className="flex h-full flex-col items-center justify-center">
<h2 className="text-center">Something went wrong! {error.message}</h2>
<button
className="mt-4 rounded-md bg-blue-500 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-400"
onClick={reload}
>
Try again
</button>
</main>
</>
);
}
error.js automatically creates a React Error Boundary that wraps a nested child segment or page.js component.
The React component exported from the error.js file is used as the fallback component.
If an error is thrown within the error boundary, the error is contained, and the fallback component is rendered.
When the fallback error component is active, layouts above the error boundary maintain their state and remain interactive, and the error component can display functionality to recover from the error.
reset function
A function to reset the error boundary. When executed, the function will try to re-render the Error boundary's contents. If successful, the fallback error component is replaced with the result of the re-render.
Can be used to prompt the user to attempt to recover from the error.