Cursorcursorintermediate

Add Error Handling to Next.js (Cursor Prompt)

Cursor prompt to add global error boundary, API error handling, and structured error logging.

What you'll get

Comprehensive error handling with error boundaries, custom error pages, API error handling, and structured logging.

The Prompt

Add comprehensive error handling to this Next.js app.

FILES TO CREATE:
- src/app/error.tsx — Global error boundary (client component)
- src/app/not-found.tsx — Custom 404 page
- src/app/global-error.tsx — Root layout error boundary
- src/lib/errors.ts — Custom error classes and error handling utilities
- src/lib/logger.ts — Structured logging utility

FILES TO MODIFY:
- src/app/api/*/route.ts — Add try/catch with consistent error responses

IMPLEMENTATION:
1. In errors.ts, create custom error classes:
   - AppError (base class with statusCode, message, code)
   - NotFoundError (404), ValidationError (400), UnauthorizedError (401), ForbiddenError (403), RateLimitError (429)
   - A handleApiError function that maps errors to JSON responses with consistent shape: { error: { message, code, statusCode } }
2. In logger.ts, create a structured logger that outputs JSON in production and pretty-prints in development. Include: timestamp, level, message, context (request ID, user ID, path), and error stack.
3. error.tsx shows a friendly error message with a "Try Again" button that calls reset(). Log the error details.
4. not-found.tsx shows a branded 404 page with search suggestions and links to popular pages.
5. Wrap all API route handlers in a withErrorHandler HOC that catches errors, logs them, and returns appropriate HTTP responses.
6. Add request ID generation (crypto.randomUUID) in middleware and pass through headers for request tracing.

DO NOT:
- Expose internal error details to users in production
- Catch errors silently without logging
- Use console.log for production logging (use the structured logger)

Replace these variables

VariableReplace with
[ERROR_TRACKING_SERVICE]Error tracking service if any (e.g., Sentry, none)

Tips for best results

Never show stack traces to users in production — log them server-side and show a generic message.

Add a request ID to every API response header so users can reference it in support tickets.

Follow-up prompts

Add Sentry

Integrate Sentry for error tracking with source maps, breadcrumbs, and user context.

Related prompts