Menu

Error Handling in Depth

Lesson 1: Error Handling in Depth

What kinds of errors are there?

Type Example How to handle
Expected Invalid form input, "course is full", wrong password Return an error value and show a message
Not found Unknown course slug Call notFound()
Unexpected Database down, bug in code Throw; caught by error.tsx
Root-level failure Error in the root layout Caught by global-error.tsx

Example

Expected error in a Server Action (returned, not thrown):

'use server';
export async function enrol(prev: State, formData: FormData): Promise<State> {
  const seats = await getSeatsLeft(String(formData.get('courseId')));
  if (seats === 0) return { message: 'This batch is full. Join the waitlist instead.' };
  // ...
}

Unexpected error boundary with retry:

// app/dashboard/error.tsx
'use client';
import { useEffect } from 'react';

export default function DashboardError({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
  useEffect(() => {
    console.error(error); // Send to your error-tracking service
  }, [error]);

  return (
    <div role="alert">
      <h2>Something went wrong loading your dashboard.</h2>
      <p>Reference: {error.digest}</p>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

Component-level boundaries (Next.js 16.3+): catchError from next/error creates a custom error boundary for any part of the tree. It does not interfere with notFound() or redirect(), and its retry() function re-fetches Server Components inside it.

'use client';
import { catchError, type ErrorInfo } from 'next/error';

function ReviewsFallback(props: { title: string }, { error, retry }: ErrorInfo) {
  return (
    <div>
      <p>{props.title} could not load.</p>
      <button onClick={() => retry()}>Retry</button>
    </div>
  );
}

export default catchError(ReviewsFallback);

How it works

  • Returning errors keeps the user on the form with a helpful message.
  • Thrown errors bubble up to the nearest boundary; the rest of the page keeps working.
  • In production, Server Component error messages are replaced with a generic message and a digest. Match the digest with your server logs to find the real error.

Common mistakes

Mistake Effect Fix
Throwing for validation errors Error page instead of a form message Return an error state
Only a root error.tsx One failing widget hides the whole page Add boundaries near risky sections
No error tracking Production bugs go unnoticed Report errors to a service such as Sentry

Key takeaways

  • Return expected errors; throw unexpected ones.
  • Place boundaries close to code that can fail, and log errors with their digest.

Try it: Add an error.tsx to the dashboard and a custom boundary around the reviews section, then force an error to see each one work.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details