Global Error Handling in JavaScript
Handle errors globally
IntermediateError HandlingExample 5 of 10
global-error-handling.js
1// Method 1: Window error handler2window.addEventListener('error', function(event) {3 console.error('Global error:', event.message);4 console.error('File:', event.filename);5 console.error('Line:', event.lineno);6 console.error('Column:', event.colno);7 console.error('Error:', event.error);89 // Send to error tracking service10 // logErrorToService(event);1112 // Prevent default browser error handling13 // return true;14});1516// Method 2: Unhandled promise rejection17window.addEventListener('unhandledrejection', function(event) {18 console.error('Unhandled promise rejection:', event.reason);19 event.preventDefault(); // Prevent default handling20});2122// Method 3: Node.js error handling23if (typeof process !== 'undefined') {24 process.on('uncaughtException', (error) => {25 console.error('Uncaught exception:', error);26 // Graceful shutdown27 process.exit(1);28 });2930 process.on('unhandledRejection', (reason, promise) => {31 console.error('Unhandled rejection:', reason);32 });33}3435// Method 4: Error boundary (React-like)36class ErrorBoundary {37 constructor() {38 this.errors = [];39 }4041 catchError(error, errorInfo) {42 this.errors.push({ error, errorInfo, timestamp: Date.now() });43 console.error('Error caught:', error, errorInfo);44 }4546 getErrors() {47 return this.errors;48 }49}5051const errorBoundary = new ErrorBoundary();5253// Method 5: Error logging service54class ErrorLogger {55 constructor() {56 this.errors = [];57 }5859 log(error, context = {}) {60 const errorEntry = {61 message: error.message,62 stack: error.stack,63 context: context,64 timestamp: new Date().toISOString(),65 userAgent: navigator.userAgent,66 url: window.location.href67 };6869 this.errors.push(errorEntry);70 // Send to server71 this.sendToServer(errorEntry);72 }7374 sendToServer(errorEntry) {75 // fetch('/api/errors', { method: 'POST', body: JSON.stringify(errorEntry) });76 console.log('Error logged:', errorEntry);77 }78}7980const errorLogger = new ErrorLogger();8182// Method 6: Error reporting83function reportError(error, context) {84 errorLogger.log(error, context);85}8687// Wrap functions with error reporting88function withErrorReporting(fn) {89 return function(...args) {90 try {91 return fn.apply(this, args);92 } catch (error) {93 reportError(error, { function: fn.name, args });94 throw error;95 }96 };97}
Output
Global error: ReferenceError: x is not defined
File: script.js
Line: 10
Column: 5
Error: ReferenceError: x is not defined
Unhandled promise rejection: Error: Promise rejected
Error caught: Error Error info
Error logged: { message: "...", stack: "...", context: {...}, timestamp: "...", userAgent: "...", url: "..." }What's going on
Global error handling catches all errors.
Window Error Handler
Catches all errors
Access error details
Log to service
Prevent default
Unhandled Rejections
Promise rejections
Handle globally
Prevent crashes
Node.js Handlers
uncaughtException
unhandledRejection
Graceful shutdown
Error Logging
Centralized logging
Include context
Send to server
Track errors
Error Reporting
Report to service
Include metadata
User context
Stack traces
Best Practices
Set up early
Log properly
Don't crash app
Monitor errors