Skip to content

ErrorBoundary

React error boundary component for graceful error handling.

ErrorBoundary catches JavaScript errors in component trees and displays a fallback UI instead of crashing the application.

  • Catches rendering errors
  • Displays user-friendly error message
  • Prevents application crash
  • Can be nested at different levels
import { ErrorBoundary } from '@cratis/components/Common';
function App() {
return (
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
);
}
  • children: Components to protect with error boundary

When an error is caught, ErrorBoundary receives:

  • error: The error object
  • errorInfo: React component stack trace
<Router>
<Route
path="/dashboard"
element={
<ErrorBoundary>
<Dashboard />
</ErrorBoundary>
}
/>
</Router>
function Dashboard() {
return (
<div>
<ErrorBoundary>
<UserStats />
</ErrorBoundary>
<ErrorBoundary>
<OrderList />
</ErrorBoundary>
<ErrorBoundary>
<RecentActivity />
</ErrorBoundary>
</div>
);
}
function DataTable() {
return (
<ErrorBoundary>
<ComplexTable data={data} />
</ErrorBoundary>
);
}

Integrate with logging services:

class LoggingErrorBoundary extends ErrorBoundary {
componentDidCatch(error, errorInfo) {
// Log to service
logErrorToService(error, errorInfo);
super.componentDidCatch(error, errorInfo);
}
}
  1. Place strategically: Use at route or feature level, not everywhere
  2. Don’t overuse: One boundary per major section is usually sufficient
  3. Log errors: Send errors to monitoring service in production
  4. Provide actions: Give users a way to recover (reload, go home)
  5. Be informative: Show helpful messages, not technical details to end users
  6. Test error states: Verify error boundaries work as expected
  7. Consider granularity: Balance between too few (whole app crashes) and too many (verbose code)
function RetryErrorBoundary({ children }) {
const [retryCount, setRetryCount] = useState(0);
const handleRetry = () => {
setRetryCount(count => count + 1);
};
// Bump `retryCount` to remount the boundary and re-render its children.
return (
<div>
<button onClick={handleRetry}>Retry</button>
<ErrorBoundary key={retryCount}>
{children}
</ErrorBoundary>
</div>
);
}

ErrorBoundary catches:

  • Rendering errors
  • Lifecycle method errors
  • Constructor errors

ErrorBoundary does NOT catch:

  • Event handler errors (use try-catch)
  • Asynchronous errors (use try-catch or .catch())
  • Server-side rendering errors
  • Errors in error boundary itself