Skip to main content

Error Boundaries

Error boundaries catch errors during route loading, rendering, and navigation, allowing you to display fallback UI instead of breaking your entire application.

Overview

TanStack Router provides built-in error boundary support at multiple levels:
  • Route-level error components
  • Router-level default error component
  • Granular error handling per route
  • Error recovery and retry mechanisms

Basic Error Handling

Route Error Component

Define error UI for individual routes:
src/routes/posts/$postId.tsx

Default Error Component

TanStack Router provides a default error component:

Router-Level Error Handling

Set a default error component for all routes:
src/main.tsx
src/components/DefaultCatchBoundary.tsx

Root Route Error Boundary

Catch errors at the application level:
src/routes/__root.tsx

Custom Error Types

Create custom error classes for better error handling:
src/utils/errors.ts
Handle them in your error component:

Error Recovery

The error component receives a reset function to retry:

Loader Errors

Errors thrown in loaders are caught by error boundaries:

Not Found vs Error

Distinguish between 404 errors and other errors:
src/routes/posts/$postId.tsx

Nested Error Boundaries

Error boundaries at different levels provide granular error handling:
src/routes/__root.tsx
src/routes/posts.tsx
src/routes/posts/$postId.tsx
Errors bubble up to the nearest error boundary.

Global Error Handling

Combine with window error handlers for comprehensive coverage:
src/main.tsx

Error Tracking Integration

Integrate with services like Sentry:

Best Practices

Granular Boundaries

Use error boundaries at multiple levels for better UX

Custom Error Types

Create specific error classes for different scenarios

User-Friendly Messages

Show helpful error messages, not technical stack traces

Error Recovery

Provide retry buttons when appropriate
Development vs Production: Show detailed error info in development, but user-friendly messages in production.
Don’t catch everything: Let critical errors bubble up. Only catch errors you can meaningfully handle.

Testing Error Boundaries

Test your error handling:

Next Steps

Route Guards

Prevent errors with validation before loading

SSR

Handle errors in server-side rendering