Skip to main content

Error Handling

Learn how to handle errors gracefully in React Router applications using error boundaries and error responses.

Overview

React Router provides a comprehensive error handling system through:
  • ErrorBoundary components for rendering errors
  • throw statements to trigger error boundaries
  • isRouteErrorResponse to identify different error types
  • Automatic error boundary inheritance from parent routes

Basic Error Boundary

Export an ErrorBoundary component from your route:

Throwing Responses

Throw HTTP responses to trigger error boundaries:

Error Responses with Data

Include structured data in error responses:

Handling Different Error Types

Handle various error scenarios:

Global Error Boundary

Handle errors at the root level:

Error Recovery

Provide ways to recover from errors:

Action Errors

Handle errors from form submissions:

Nested Error Boundaries

Use route hierarchy for contextual error handling:

Error Logging

Log errors to external services:

Development vs Production

Show detailed errors in development:

Best Practices

  1. Always provide error boundaries - At least at the root level
  2. Use semantic status codes - 404 for not found, 403 for forbidden, etc.
  3. Provide recovery options - Help users get back on track
  4. Log errors - Track issues in production
  5. Show appropriate detail - More in development, less in production
  6. Handle expected errors - Validate and throw descriptive errors
  7. Use nested boundaries - Provide context-specific error handling
  8. Test error scenarios - Ensure error boundaries work correctly