Next.js Patterns

Error Handling

Error boundaries, not-found pages, global errors, and graceful degradation.

Advertisement

Error Handling

Error boundaries, not-found pages, global errors, and graceful degradation.

Overview

Proper error handling improves user experience and debugging.

Key Concepts

  • error.js — Route-specific error boundaries
  • not-found.js — Custom 404 pages
  • global-error.js — Root-level error handling
  • Error Recovery — Retry mechanisms
  • Error Reporting — Log errors to services

Code Examples

// app/dashboard/error.js
'use client';

export default function Error({ error, reset }) {
  return (
    <div className="error-container">
      <h2>Something went wrong!</h2>
      <p>{error.message}</p>
      <button onClick={reset}>Try again</button>
    </div>
  );
}

// app/not-found.js
export default function NotFound() {
  return (
    <div>
      <h2>404 - Page Not Found</h2>
      <p>The page you're looking for doesn't exist.</p>
      <a href="/">Go home</a>
    </div>
  );
}

// app/global-error.js
'use client';

export default function GlobalError({ error, reset }) {
  return (
    <html>
      <body>
        <h2>Something went wrong!</h2>
        <button onClick={reset}>Try again</button>
      </body>
    </html>
  );
}

// notFound() in server components
async function ProductPage({ params }) {
  const product = await getProduct(params.id);
  
  if (!product) {
    notFound();
  }

  return <ProductDetails product={product} />;
}

Practice

Implement comprehensive error handling with custom error pages and recovery.