patternjavascriptreactMajorpending
Error Boundaries and Graceful Degradation Patterns
Viewed 0 times
error boundarygraceful degradationfallbackcrash recoveryresilience
Problem
A single JavaScript error in one component crashes the entire application. Users see a blank white screen with no way to recover.
Solution
Implement error boundaries and graceful degradation:
Key principles:
// React Error Boundary
class ErrorBoundary extends React.Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, info) {
// Log to error reporting service
reportError(error, info.componentStack);
}
render() {
if (this.state.hasError) {
return this.props.fallback || (
<div role="alert">
<h2>Something went wrong</h2>
<button onClick={() => this.setState({ hasError: false })}>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
// Usage: isolate failure zones
<ErrorBoundary fallback={<p>Feed unavailable</p>}>
<NewsFeed />
</ErrorBoundary>
<ErrorBoundary fallback={<p>Chat offline</p>}>
<ChatWidget />
</ErrorBoundary>
// If ChatWidget crashes, NewsFeed still works!
// Generic graceful degradation hook
function useGraceful(asyncFn, fallbackValue) {
const [data, setData] = useState(fallbackValue);
const [error, setError] = useState(null);
useEffect(() => {
asyncFn()
.then(setData)
.catch(err => {
setError(err);
reportError(err);
// Return fallback - don't crash
});
}, []);
return { data, error, isError: !!error };
}Key principles:
- Isolate failure zones (each section has its own boundary)
- Provide fallback UI (not just blank space)
- Allow recovery (retry buttons, refresh)
- Report errors automatically (Sentry, Datadog)
- Never show raw error messages to users
Why
Error boundaries prevent one broken feature from taking down the entire application. Users can continue using working parts while the broken section shows a helpful fallback.
Gotchas
- Error boundaries only catch render/lifecycle errors - NOT event handlers or async code
- Wrap error boundaries around independent features, not around every component
Context
Building resilient frontend applications
Revisions (0)
No revisions yet.