Skip to main content

Error Boundaries

Class-Based Error Boundary

import React, { Component, ReactNode } from 'react';

interface Props {
children: ReactNode;
fallback?: ReactNode;
}

interface State {
hasError: boolean;
error: Error | null;
}

class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false, error: null };
}

static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}

componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error('Error caught by boundary:', error, errorInfo);
// Log to error reporting service
logErrorToService(error, errorInfo);
}

render() {
if (this.state.hasError) {
return (
this.props.fallback || (
<div>
<h1>Something went wrong</h1>
<button onClick={() => this.setState({ hasError: false })}>
Try again
</button>
</div>
)
);
}

return this.props.children;
}
}

// Usage
<ErrorBoundary fallback={<ErrorFallback />}>
<App />
</ErrorBoundary>;

Multiple Error Boundaries

function App() {
return (
<ErrorBoundary fallback={<AppError />}>
<Header />
<ErrorBoundary fallback={<SidebarError />}>
<Sidebar />
</ErrorBoundary>
<ErrorBoundary fallback={<ContentError />}>
<MainContent />
</ErrorBoundary>
</ErrorBoundary>
);
}

Error Boundary with Reset

class ErrorBoundary extends Component {
state = { hasError: false, error: null };

static getDerivedStateFromError(error) {
return { hasError: true, error };
}

resetError = () => {
this.setState({ hasError: false, error: null });
};

render() {
if (this.state.hasError) {
return (
<ErrorFallback error={this.state.error} resetError={this.resetError} />
);
}

return this.props.children;
}
}

Best Practices

  1. Use multiple boundaries - Isolate errors
  2. Log errors - Send to monitoring service
  3. Provide recovery - Allow users to retry
  4. Show helpful messages - User-friendly errors
  5. Development vs Production - Different fallbacks