ErrorBoundary
React error boundary component for graceful error handling.
Purpose
Section titled “Purpose”ErrorBoundary catches JavaScript errors in component trees and displays a fallback UI instead of crashing the application.
Key Features
Section titled “Key Features”- Catches rendering errors
- Displays user-friendly error message
- Prevents application crash
- Can be nested at different levels
Basic Usage
Section titled “Basic Usage”import { ErrorBoundary } from '@cratis/components/Common';
function App() { return ( <ErrorBoundary> <MyComponent /> </ErrorBoundary> );}children: Components to protect with error boundary
Error Information
Section titled “Error Information”When an error is caught, ErrorBoundary receives:
error: The error objecterrorInfo: React component stack trace
Usage Patterns
Section titled “Usage Patterns”Route Level
Section titled “Route Level”<Router> <Route path="/dashboard" element={ <ErrorBoundary> <Dashboard /> </ErrorBoundary> } /></Router>Feature Level
Section titled “Feature Level”function Dashboard() { return ( <div> <ErrorBoundary> <UserStats /> </ErrorBoundary>
<ErrorBoundary> <OrderList /> </ErrorBoundary>
<ErrorBoundary> <RecentActivity /> </ErrorBoundary> </div> );}Component Level
Section titled “Component Level”function DataTable() { return ( <ErrorBoundary> <ComplexTable data={data} /> </ErrorBoundary> );}Error Logging
Section titled “Error Logging”Integrate with logging services:
class LoggingErrorBoundary extends ErrorBoundary { componentDidCatch(error, errorInfo) { // Log to service logErrorToService(error, errorInfo);
super.componentDidCatch(error, errorInfo); }}Best Practices
Section titled “Best Practices”- Place strategically: Use at route or feature level, not everywhere
- Don’t overuse: One boundary per major section is usually sufficient
- Log errors: Send errors to monitoring service in production
- Provide actions: Give users a way to recover (reload, go home)
- Be informative: Show helpful messages, not technical details to end users
- Test error states: Verify error boundaries work as expected
- Consider granularity: Balance between too few (whole app crashes) and too many (verbose code)
Recovery Mechanisms
Section titled “Recovery Mechanisms”Auto-Retry
Section titled “Auto-Retry”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> );}What Errors Are Caught
Section titled “What Errors Are Caught”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