Course contentsShow
← React
Lesson 1297 of 2,39633. Error BoundariesFree lesson

Handling Non-Boundary Errors: Global Error Events

For errors error boundaries miss, use window.addEventListener('error') or 'unhandledrejection' for promises.

Handling Non-Boundary Errors: Global Error Events

What you'll learn: How to catch errors that slip through React's error boundaries using browser-level event listeners.

The Gap Error Boundaries Leave

Error boundaries are powerful for catching render errors, but as you've learned, they miss several categories of problems: event handler errors, async code failures, and errors in their own rendering. When these occur, they don't crash your UI—but they might silently fail or only appear in the console, leaving your app in a broken state without user-facing feedback.

Global Safety Nets

The browser provides two global event listeners that catch errors error boundaries can't:

window.addEventListener('error') catches synchronous runtime errors anywhere in your application, including event handlers and non-React code.

window.addEventListener('unhandledrejection') catches Promise rejections that don't have .catch() handlers—common with async/await code.

When to Use These

Set up these listeners once in your app (typically in index.js or a root component) to log errors to monitoring services, show user notifications, or provide fallback behavior:

// In your app initialization
window.addEventListener('error', (event) => {
  console.error('Global error caught:', event.error);
  // Log to monitoring service, show notification, etc.
});

window.addEventListener('unhandledrejection', (event) => {
  console.error('Unhandled promise rejection:', event.reason);
  // Handle async errors that escaped try/catch
});

Think of error boundaries as safety nets for your trapeze act (rendering), while global event listeners are the padding on the ground below—they catch everything else that falls through.

Key Takeaway: Error boundaries handle React's rendering tree, but window.addEventListener('error') and 'unhandledrejection' provide essential safety nets for event handlers, async code, and other gaps in error boundary coverage.