Next.js Error Handling — error.tsx & Error Boundaries
error.tsx, same folder route లో ఏదైనా error throw అయితే, automatic గా fallback UI గా చూపబడుతుంది. Idి tప్పనిసరిగా Client Component గా ఉండాలి:
"use client";
export default function ErrorPage({
error,
reset,
}: {
error: Error;
reset: () => void;
}) {
return (
<div>
<h2>Something went wrong.</h2>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
);
}
"use client": error.tsx ఎప్పుడూ Client Component గానే ఉండాలి — React error boundary mechanism client meedhа depend అవుతుంది.error: Thrown error object, message తో పాటు.reset(): Route ni మళ్ళీ render చేయడానికి try చేసే function — "Try again" button కి attach చేస్తారు.
URL కి matching route దొరకనప్పుడు, లేదా code లో manual గా notFound() call చేసినప్పుడు, not-found.tsx చూపబడుతుంది:
import { notFound } from "next/navigation";
export default async function CoursePage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const course = await fetch(`https://api.example.com/courses/${slug}`).then((r) => r.json());
if (!course) {
notFound();
}
return <h1>{course.title}</h1>;
}
notFound() call చేస్తే, Next.js immediately execution stop చేసి, దగ్గరలో unна not-found.tsx render చేస్తుంది.
error.tsx, ఆ specific segment మరియు దాని children matrame catch చేస్తుంది — layout.tsx లో error వస్తే, same-level error.tsx catch చేయదు (parent level error.tsx కావాలి). Root-level errors కోసం app/global-error.tsx special file వాడాలి.
error.message ni direct ga UI లో చూపించడం — production లో database connection strings, stack traces లాంటి sensitive info leak అవ్వచ్చు. Production error.tsx లో, generic user-friendly message చూపించి, actual error ని server-side logging service కి matrame pంపాలి.
Create an error.tsx for an 'orders' section that shows a friendly message and a button to navigate back home.
"use client";
import Link from "next/link";
export default function OrdersError({ reset }: { reset: () => void }) {
return (
<div>
<h2>We couldn't load your orders.</h2>
<button onClick={() => reset()}>Retry</button>
<Link href="/">Go Home</Link>
</div>
);
}
Q error.tsx Server Component గా ఉండొచ్చా?
Ledు, తప్పనిసరిగా 'use client' తో Client Component గా ఉండాలి — React's error boundary API client-side mechanism.
Q reset() function ఎప్పుడు పనిచేయదు?
Error, రూట్ layout లోనే వస్తే (component tree మొత్తం broken అయితే), reset() సరిగ్గా recover కాకపోవచ్చు — అలాంటప్పుడు full page reload better option.
Q notFound() ఎప్పుడు వాడాలి, throw new Error ఎప్పుడు వాడాలి?
Data దొరకకపోతే (404 scenario) notFound() వాడాలి — ఇది not-found.tsx trigger చేస్తుంది. Unexpected failures (API down, DB error) కోసం throw new Error వాడాలి — ఇది error.tsx trigger చేస్తుంది.