typescriptintermediate

Error Handling with error.tsx and not-found.tsx

Handle errors gracefully with error.tsx boundaries and not-found.tsx pages in App Router.

typescript
// app/dashboard/error.tsx
'use client';

export default function DashboardError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  return (
    <div className="flex flex-col items-center justify-center min-h-[400px]">
      <h2 className="text-xl font-bold mb-2">Something went wrong!</h2>
      <p className="text-gray-500 mb-4">{error.message}</p>
      <button
        onClick={reset}
        className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
      >
        Try again
      </button>
    </div>
  );
}

// app/dashboard/not-found.tsx
import Link from 'next/link';

export default function DashboardNotFound() {
  return (
    <div className="flex flex-col items-center justify-center min-h-[400px]">
      <h2 className="text-2xl font-bold mb-2">Not Found</h2>
      <p className="text-gray-500 mb-4">Could not find the requested resource</p>
      <Link href="/dashboard" className="text-blue-500 hover:underline">
        Return to Dashboard
      </Link>
    </div>
  );
}

// app/global-error.tsx (catches root layout errors)
'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>
  );
}

Use Cases

  • error boundaries
  • 404 pages
  • graceful degradation

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.