4 min read
ā¢Question 8 of 47easyHow to handle errors in Next.js?
Using error.tsx and error boundaries.
What You'll Learn
- error.tsx file
- Error recovery
- Global error handling
error.tsx
code.txtTSX
'use client'; // Must be client component
import { useEffect } from 'react';
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<div>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</div>
);
}Global Error (Root Layout)
code.txtTSX
// app/global-error.tsx
'use client';
export default function GlobalError({
error,
reset,
}: {
error: Error;
reset: () => void;
}) {
return (
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
);
}Not Found Page
code.txtTSX
// app/not-found.tsx
export default function NotFound() {
return (
<div>
<h2>Page Not Found</h2>
<p>Could not find the requested page.</p>
</div>
);
}
// Trigger programmatically
import { notFound } from 'next/navigation';
async function getPost(slug: string) {
const post = await db.post.find(slug);
if (!post) notFound();
return post;
}