Global Error Handling

Handle errors globally

JavaScriptIntermediate
JavaScript
// Method 1: Window error handler
window.addEventListener('error', function(event) {
    console.error('Global error:', event.message);
    console.error('File:', event.filename);
    console.error('Line:', event.lineno);
    console.error('Column:', event.colno);
    console.error('Error:', event.error);
    
    // Send to error tracking service
    // logErrorToService(event);
    
    // Prevent default browser error handling
    // return true;
});

// Method 2: Unhandled promise rejection
window.addEventListener('unhandledrejection', function(event) {
    console.error('Unhandled promise rejection:', event.reason);
    event.preventDefault(); // Prevent default handling
});

// Method 3: Node.js error handling
if (typeof process !== 'undefined') {
    process.on('uncaughtException', (error) => {
        console.error('Uncaught exception:', error);
        // Graceful shutdown
        process.exit(1);
    });
    
    process.on('unhandledRejection', (reason, promise) => {
        console.error('Unhandled rejection:', reason);
    });
}

// Method 4: Error boundary (React-like)
class ErrorBoundary {
    constructor() {
        this.errors = [];
    }
    
    catchError(error, errorInfo) {
        this.errors.push({ error, errorInfo, timestamp: Date.now() });
        console.error('Error caught:', error, errorInfo);
    }
    
    getErrors() {
        return this.errors;
    }
}

const errorBoundary = new ErrorBoundary();

// Method 5: Error logging service
class ErrorLogger {
    constructor() {
        this.errors = [];
    }
    
    log(error, context = {}) {
        const errorEntry = {
            message: error.message,
            stack: error.stack,
            context: context,
            timestamp: new Date().toISOString(),
            userAgent: navigator.userAgent,
            url: window.location.href
        };
        
        this.errors.push(errorEntry);
        // Send to server
        this.sendToServer(errorEntry);
    }
    
    sendToServer(errorEntry) {
        // fetch('/api/errors', { method: 'POST', body: JSON.stringify(errorEntry) });
        console.log('Error logged:', errorEntry);
    }
}

const errorLogger = new ErrorLogger();

// Method 6: Error reporting
function reportError(error, context) {
    errorLogger.log(error, context);
}

// Wrap functions with error reporting
function withErrorReporting(fn) {
    return function(...args) {
        try {
            return fn.apply(this, args);
        } catch (error) {
            reportError(error, { function: fn.name, args });
            throw error;
        }
    };
}

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

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