How to Catch all JavaScript Errors and Send them to the Server?

JavaScript error handling is crucial for maintaining robust web applications. The window.onerror event allows you to catch all JavaScript errors globally and send them to your server for monitoring and debugging purposes.

Understanding window.onerror

The window.onerror event fires whenever an uncaught JavaScript error occurs in your application. It provides detailed information about the error including location and error details.

Syntax

window.onerror = (message, source, lineno, colno, error) => {
    // Handle error
};

Parameters

  • message: A string containing the error message that describes what went wrong.

  • source: A string containing the URL of the script file where the error occurred.

  • lineno: An integer representing the line number where the error occurred.

  • colno: An integer representing the column number where the error occurred.

  • error: The actual Error object that was thrown.

Basic Error Catching Example

Here's a simple example that demonstrates how to catch JavaScript errors using window.onerror:

<!DOCTYPE html>
<html>
<head>
    <title>Basic Error Catching</title>
</head>
<body>
    <h3>JavaScript Error Catching Demo</h3>
    <div id="errorDisplay"></div>
    
    <script>
        window.onerror = (message, source, lineno, colno, error) => {
            let errorInfo = `Error: ${message} at line ${lineno}, column ${colno}`;
            document.getElementById("errorDisplay").innerHTML = errorInfo;
            return true; // Prevents default browser error handling
        };
        
        // This will trigger an error
        let result = undefinedVariable + 10;
    </script>
</body>
</html>

Complete Error Logging System

Here's a comprehensive example that catches errors and sends them to a server:

<!DOCTYPE html>
<html>
<head>
    <title>Error Logging System</title>
    <style>
        #sendBtn {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        #status {
            margin-top: 10px;
            padding: 10px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <h3>JavaScript Error Logging System</h3>
    <button id="sendBtn">Send Errors to Server</button>
    <div id="status"></div>
    
    <script>
        let errorLog = [];
        
        // Global error handler
        window.onerror = (message, source, lineno, colno, error) => {
            let errorData = {
                message: message,
                source: source,
                line: lineno,
                column: colno,
                timestamp: new Date().toISOString(),
                userAgent: navigator.userAgent,
                url: window.location.href
            };
            
            errorLog.push(errorData);
            updateStatus(`Error logged: ${message}`);
            return true;
        };
        
        // Function to send errors to server
        function sendErrorsToServer() {
            if (errorLog.length === 0) {
                updateStatus("No errors to send");
                return;
            }
            
            let xhr = new XMLHttpRequest();
            xhr.open('POST', '/api/errors', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        updateStatus(`Successfully sent ${errorLog.length} error(s) to server`);
                        errorLog = []; // Clear the log after successful send
                    } else {
                        updateStatus('Failed to send errors to server');
                    }
                }
            };
            
            xhr.send(JSON.stringify({ errors: errorLog }));
        }
        
        function updateStatus(message) {
            document.getElementById('status').innerHTML = message;
        }
        
        // Attach event listener to button
        document.getElementById('sendBtn').onclick = sendErrorsToServer;
        
        // Simulate an error for demonstration
        setTimeout(() => {
            try {
                nonExistentFunction();
            } catch (e) {
                // This won't be caught by window.onerror since it's in a try-catch
                throw e; // Re-throw to trigger window.onerror
            }
        }, 1000);
    </script>
</body>
</html>

Server-Side Error Handler (Node.js/Express)

Here's a simple Express.js server to receive and process the error data:

const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('public')); // Serve static files

// Error logging endpoint
app.post('/api/errors', (req, res) => {
    const { errors } = req.body;
    
    if (!errors || !Array.isArray(errors)) {
        return res.status(400).json({ error: 'Invalid error data' });
    }
    
    // Process each error
    errors.forEach(error => {
        console.log('JavaScript Error Received:');
        console.log(`Message: ${error.message}`);
        console.log(`Source: ${error.source}`);
        console.log(`Line: ${error.line}, Column: ${error.column}`);
        console.log(`Timestamp: ${error.timestamp}`);
        console.log(`User Agent: ${error.userAgent}`);
        console.log(`Page URL: ${error.url}`);
        console.log('-------------------');
        
        // Here you could save to database, send to logging service, etc.
    });
    
    res.json({ 
        success: true, 
        message: `Processed ${errors.length} error(s)` 
    });
});

app.listen(port, () => {
    console.log(`Error logging server running on port ${port}`);
});

Modern Alternatives

While window.onerror is widely supported, modern browsers also support window.addEventListener('error') and window.addEventListener('unhandledrejection') for Promise rejections:

// Alternative modern approach
window.addEventListener('error', (event) => {
    console.log('Error caught:', event.error);
});

// For unhandled Promise rejections
window.addEventListener('unhandledrejection', (event) => {
    console.log('Unhandled promise rejection:', event.reason);
});

Key Benefits

  • Real-time monitoring: Catch errors as they happen in production

  • User context: Collect browser info, URL, and timestamp for debugging

  • Proactive debugging: Find issues before users report them

  • Performance insights: Track error frequency and patterns

Conclusion

Using window.onerror with XMLHttpRequest provides a robust solution for catching and logging JavaScript errors to your server. This enables proactive error monitoring and improves the overall reliability of your web applications.

Updated on: 2026-03-15T23:19:01+05:30

553 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements