Global Error Handling

Handle errors globally

IntermediateTopic: Error Handling
Back

JavaScript Global Error Handling Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// 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: "..." }

Understanding Global Error Handling

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

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Global Error Handling

This JavaScript program is part of the "Error Handling" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents