class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error(
'ErrorBoundary caught:', error, errorInfo
);
// In production: send to error tracking
// service (Sentry)
}
render() {
if (this.state.hasError) {
return this.props.fallback || (
<div className="p-8 text-center">
<h2 className="text-xl font-bold
text-red-400">
Something went wrong
</h2>
<p className="text-slate-400 mt-2">
{this.state.error?.message}
</p>
<button
className="mt-4 px-4 py-2
bg-cyan-600 rounded"
onClick={() => this.setState({
hasError: false, error: null
})}
>
Try Again
</button>
</div>
);
}
return this.props.children;
}
}
function App() {
return (
<Layout>
<ErrorBoundary
fallback={<p>Toolbar error</p>}>
<Toolbar />
</ErrorBoundary>
<ErrorBoundary fallback={
<p>Canvas error — try reloading
your image</p>
}>
<CanvasArea />
</ErrorBoundary>
<ErrorBoundary
fallback={<p>Settings error</p>}>
<SettingsPanel />
</ErrorBoundary>
</Layout>
);
}
Deliberately throw an error in a component → boundary catches it → other panels still work. The canvas keeps rendering while the settings panel shows "Something went wrong."
Error boundaries catch render errors, NOT event handler errors (those need try/catch).
| Error Type | Caught by Boundary? | Solution |
|---|---|---|
| Render error (throw in JSX) | ✅ Yes | ErrorBoundary |
| Lifecycle error | ✅ Yes | ErrorBoundary |
| Event handler (onClick) | ❌ No | try/catch |
| Async error (fetch) | ❌ No | .catch() / try-catch |
| Server-side rendering | ❌ No | SSR error handling |
Collect error details (error message, component stack, timestamp) and offer a "Report Bug" button in the fallback UI. In production, this sends to an error tracking service like Sentry.
git switch -c bugfix/PIXELCRAFT-042-error-boundaries
git add src/
git commit -m "Add error boundaries for crash recovery (PIXELCRAFT-042)"
git push origin bugfix/PIXELCRAFT-042-error-boundaries
# PR → Review → Merge → Close ticket ✅
Fault isolation.
A failure in one part shouldn't crash the entire system. This is the "bulkhead pattern" — from ship compartments.