054
LVL 02 — CIRCUIT BREAKER SESSION 054 DAY 54

ERROR BOUNDARIES

🎫 PIXELCRAFT-042
🐛 Bug / 🔧 Refactor | 🟡 Medium | Priority: 🟠 High

When a React component throws an error during rendering, the ENTIRE app crashes to a white screen. We need error boundaries to catch rendering errors and show a recovery UI.
CONCEPTS.UNLOCKED
🛡
Error Boundaries
Class components that catch JavaScript errors in their child tree. Instead of the whole app crashing to white, the boundary catches the error and shows a recovery UI.
componentDidCatch & getDerivedStateFromError
getDerivedStateFromError(error) updates state to show fallback UI. componentDidCatch(error, info) logs the error for debugging or sends to an error tracking service.
🔄
Recovery UI
"Something went wrong. Try again" instead of a white screen. Show the error message, a retry button, and optionally a "Report Bug" link. Graceful degradation.
📍
Boundary Placement
Place boundaries around independent features, not around every component. Toolbar, Canvas, and SettingsPanel each get their own boundary. A crash in one doesn't affect the others.
Limitations
Error boundaries don't catch: event handler errors (use try/catch), async errors (use .catch()), server-side rendering errors. They only catch errors during rendering and lifecycle methods.
🚢
Bulkhead Pattern
From ship design: a leak in one compartment doesn't sink the ship. Error boundaries apply the same principle to UI — isolate failures to prevent cascading crashes.
HANDS-ON.TASKS
01
Create a Reusable ErrorBoundary
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; } }
This is a class component — the only remaining use case for class components in modern React. Error boundaries cannot be written as function components (no hook equivalent for getDerivedStateFromError).
02
Wrap Independent Features
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> ); }
Each major section has its own boundary. If SettingsPanel crashes, Toolbar and CanvasArea keep working. The user can still use the app while the broken panel shows a recovery UI.
03
Test: Deliberate Crash

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."

04
Understand the Limitations

Error boundaries catch render errors, NOT event handler errors (those need try/catch).

Error TypeCaught by Boundary?Solution
Render error (throw in JSX)✅ YesErrorBoundary
Lifecycle error✅ YesErrorBoundary
Event handler (onClick)❌ Notry/catch
Async error (fetch)❌ No.catch() / try-catch
Server-side rendering❌ NoSSR error handling
05
Add a "Report Bug" Button

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.

06
Close the Ticket
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 ✅
CS.DEEP-DIVE

Fault isolation.

A failure in one part shouldn't crash the entire system. This is the "bulkhead pattern" — from ship compartments.

// Fault isolation everywhere:

Ships            → a leak in one compartment
                   doesn't sink the ship
Operating systems → one crashed app doesn't
                   crash the OS
Microservices    → one failed service doesn't
                   take down the platform
React boundaries → one crashed panel doesn't
                   kill the app

// Designing for partial failure is a
// hallmark of mature engineering.
"Resilience Lab"
[A] Create a "Chaos Mode" toggle in dev settings that randomly throws errors in components. Use it to verify every boundary catches errors correctly and shows appropriate recovery UI.
[B] Add error logging with timestamps, component stack traces, and user actions that led to the crash. Build a simple error log viewer in the settings page.
[C] Research the react-error-boundary library. Compare its API (useErrorBoundary hook, resetKeys) with the class-based approach. Refactor to use it and evaluate the difference.
REF.MATERIAL
ARTICLE
React Team
Official reference: getDerivedStateFromError, componentDidCatch, fallback UI, and where to place boundaries in the component tree.
ERROR BOUNDARYOFFICIALESSENTIAL
VIDEO
Web Dev Simplified
Practical walkthrough: building error boundaries, placement strategy, recovery UI, and the react-error-boundary library.
ERROR BOUNDARYPRACTICAL
ARTICLE
Brian Vaughn
Production-ready error boundary library: useErrorBoundary hook, resetKeys for automatic recovery, ErrorBoundary component with modern API.
LIBRARYPRODUCTION
ARTICLE
Wikipedia
The engineering principle behind error boundaries: isolate compartments so a failure in one doesn't cascade. From shipbuilding to software architecture.
ARCHITECTUREPATTERNCS
ARTICLE
Sentry
Production error tracking: capture errors from boundaries, track stack traces, monitor error rates. The industry standard for error monitoring in React apps.
SENTRYPRODUCTIONMONITORING
// LEAVE EXCITED BECAUSE
A crash in the settings panel no longer kills the whole app. The canvas keeps working. Users see a recovery UI instead of a white screen. This is production-grade resilience.