Error Boundaries & Global Exception Catching0%

Error Boundaries & Global Exception Catching

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

Error Boundaries & Global Exception Catching in Modern JavaScript

Even with disciplined try...catch handling, unanticipated exceptions slip through in complex frontend and backend systems. Establishing Global Exception Catching and Error Boundary Patterns ensures that a single crash in an isolated widget does not bring down the entire application or leave users staring at a frozen white screen.


1. Browser Global Exception Catching Architecture

Browsers provide two primary global handlers:

Output
┌─────────────────────────────────────────────────────────────┐
│ GLOBAL EXCEPTION SYSTEM │
├──────────────────────────────┬──────────────────────────────┤
│ window.onerror / 'error' │ Synchronous JS exceptions, │
│ │ DOM event errors │
├──────────────────────────────┼──────────────────────────────┤
│ window.onunhandledrejection │ Uncaught Promise rejections, │
│ │ unhandled async/await errors │
└──────────────────────────────┴──────────────────────────────┘

Implementing Global Listeners:

JavaScript
// 1. Capture synchronous runtime exceptions
window.addEventListener('error', (event) => {
console.error('[Global Error]:', {
message: event.message,
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
error: event.error
});
 
// Report to telemetry service
telemetryReporter.sendCrashReport(event.error);
});
 
// 2. Capture unhandled Promise rejections
window.addEventListener('unhandledrejection', (event) => {
console.error('[Unhandled Promise Rejection]:', event.reason);
 
// Prevent default red console error if desired:
// event.preventDefault();
telemetryReporter.sendPromiseCrash(event.reason);
});

2. Cross-Origin Script Errors ("Script error.")

When loading scripts from CDNs without CORS headers, cross-origin security restrictions obscure error messages, producing an unhelpful Script error. with line number 0.

The Fix: Add crossorigin="anonymous"

HTML
<!-- In HTML: Enable CORS header on script tag -->
<script src="https://cdn.example.com/lib.js" crossorigin="anonymous"></script>

And ensure the CDN responds with HTTP header: `Access-Control-Allow-Origin: `.*


3. Vanilla JS Error Boundary Pattern

While popular in React, the Error Boundary pattern can be implemented in Vanilla JavaScript to wrap interactive components:

JavaScript
class UIErrorBoundary {
constructor(containerElement, fallbackRenderFn) {
this.container = containerElement;
this.fallbackRender = fallbackRenderFn;
}
 
wrap(componentFunction) {
return async (...args) => {
try {
await componentFunction(...args);
} catch (error) {
console.error(`[ErrorBoundary] Caught crash in component:`, error);
// Render user-friendly fallback UI instead of crashing whole page!
this.container.innerHTML = this.fallbackRender(error);
// Report telemetry
telemetryReporter.sendCrashReport(error);
}
};
}
}
 
// Usage:
const chartContainer = document.querySelector('#crypto-chart');
const boundary = new UIErrorBoundary(chartContainer, (err) => `
<div class="card card-error">
<h4>Unable to display Chart</h4>
<p>${err.message}</p>
<button onclick="location.reload()">Retry</button>
</div>
`);
 
const safeRenderChart = boundary.wrap(async () => {
// Risky 3rd-party rendering logic
renderComplexFinancialChart();
});
 
safeRenderChart();

Interactive Quiz

Practice Quiz

Question 1
What event captures unhandled Promise rejections in modern browsers?
Question 2
Why does window.onerror sometimes report the vague message "Script error." on line 0?
Question 3
What is the primary purpose of an Error Boundary?
Question 4
How do you prevent the browser from logging its default red error message for an unhandled rejection?
Question 5
In Node.js, what process event is triggered by unhandled exceptions?
Next Lesson

Memory Leak Detection & Heap Snapshots

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext