Error Collection

Capture JavaScript runtime errors, unhandled promise rejections, and resource loading errors to investigate production failures.

🎯 Introduction

During local development, errors are easy to spot in the console. In a user's browser, you cannot directly see what failed or on which line. Error collection listens for errors globally in that browser and automatically reports them to a server, giving you records to investigate.

By the end of this article, you will be able to:

  • Capture JavaScript runtime errors with window.onerror, including messages, locations, and stack traces.
  • Cover unhandled promise rejections with the unhandledrejection event.
  • Capture resource loading errors that do not bubble using a capture-phase error listener.
  • Combine all three into a reusable collection and reporting module for your project.

🧱 JavaScript Runtime Errors: window.onerror

try/catch handles risks you anticipate, but cannot wrap every piece of code. window.onerror provides a global fallback for uncaught runtime errors:

monitor.js
window.onerror = function (message, source, lineno, colno, error) {
    console.log('Error message:', message); // For example, "Cannot read properties of undefined"
    console.log('Source file:', source); // For example, "https://example.com/app.js"
    console.log('Error location:', lineno, colno); // Line and column numbers
    console.log('Stack trace:', error.stack); // Complete call stack

    // Returning true marks the error as handled and suppresses the browser's console error
    // Usually, leave the console error visible to make local debugging easier
};

Of these five arguments, error.stack is especially useful: the message, file, and line locate the error, while the stack trace shows the sequence of calls that led to it.

You can also use window.addEventListener('error', handler) to listen for these errors and attach multiple listeners. We will use that approach below because it also supports resource loading errors.

If JavaScript is served from another origin, such as a CDN, without cross-origin configuration, window.onerror may only receive the unhelpful message "Script error." Add a crossorigin attribute to the script tag and configure the CDN to return the appropriate CORS response headers.

🧱 Unhandled Promise Rejections: unhandledrejection

An unhandled promise rejection does not trigger window.onerror; it only produces a console warning:

demo.js
// Without catch, a failed request is not handled by your application
// The same applies to async/await when await is not wrapped in try/catch
fetch('/api/user').then((res) => res.json());

Use the dedicated unhandledrejection event to capture it:

monitor.js
window.addEventListener('unhandledrejection', (event) => {
    // event.reason contains the promise's rejection reason
    console.log('Unhandled promise rejection:', event.reason);
});

event.reason is not necessarily an Error object: a string such as reject('Network timeout') is valid too. Handle both cases: read stack from Error objects and convert other values to strings.

Rejections handled with .catch() or try/catch do not trigger this event. Continue handling expected errors normally; the global listener is a fallback for unhandled ones.

🧱 Resource Loading Errors: Capture-Phase error Events

Resource loading errors, such as image 404s or failed script downloads, may leave the page running but break styles or features. The catch is that their error events do not bubble, so an ordinary window listener misses them.

To understand the solution, recall DOM event propagation. During the capture phase, the event travels from window down to its target. During the bubbling phase, it travels back up; listeners use this phase by default. A resource loading error does not travel back up, but still travels down to its target. Listen during capture by passing true as the third argument to addEventListener.

A capture-phase error listener also receives runtime errors. Distinguish them using event.target: runtime errors target window, while resource loading errors target an element such as img, script, or link. Read its src or href to identify the resource. The next section puts this together.


🧰 A Shared Collection and Reporting Module

Combine the three error types into a module and import it once at your application entry point:

monitor.js
// Report error data to your server
function report(data) {
    // navigator.sendBeacon suits monitoring reports:
    // the browser attempts delivery even while the page is closing
    const body = JSON.stringify(data);
    navigator.sendBeacon('/api/monitor', body);
}

// Runtime and resource loading errors: listen during capture and distinguish by target
window.addEventListener(
    'error',
    (event) => {
        if (event.target && event.target !== window) {
            // Resource loading error
            report({
                type: 'resource',
                url: event.target.src || event.target.href,
                tag: event.target.tagName,
            });
        } else {
            // JavaScript runtime error
            report({
                type: 'runtime',
                message: event.message,
                file: event.filename,
                line: event.lineno,
                stack: event.error && event.error.stack,
            });
        }
    },
    true
);

// Unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
    const reason = event.reason;
    report({
        type: 'promise',
        message: reason instanceof Error ? reason.message : String(reason),
        stack: reason instanceof Error ? reason.stack : '',
    });
});
main.js
import './monitor';

In production, also include the page URL, user identifier, and timestamp in each report, and deduplicate identical errors so a single refresh does not flood the server with repeated records.

Vue also provides app.config.errorHandler for errors thrown during component rendering and lifecycle hooks, complementing global listeners. Mature tools such as Sentry build on these APIs. We will cover Sentry integration later in this course.

❓ Questions and Answers

Q1: Why use global error listeners if I already use try/catch?

try/catch covers code where you anticipate a risk, not the entire application. Global listeners catch unexpected errors as a fallback. Use both together.

Q2: Can try/catch catch errors in promises?

It depends on the syntax. Wrapping promise.then() does not catch errors inside its callbacks; use .catch() or unhandledrejection. With async/await, wrapping the await expression in try/catch catches its rejection through the sequential control flow.

Q3: Why don't resource loading errors bubble?

This is how DOM events are designed: a loading failure describes the resource's own state rather than its position in the DOM, so ancestors do not need a bubbling notification. The event still passes through capture on its way to the target, where a capture-phase listener can intercept it.

Q4: Why report with sendBeacon instead of fetch?

Errors can occur just as users close the page, when fetch may be canceled. sendBeacon is designed to send data even during page unloading. Its limitations include a payload size limit and no access to the response.

Q5: Are reported line numbers, column numbers, and stack traces useful when production code is minified?

Not very useful on their own. Source maps generated at build time map those positions back to the original source. Doing this manually is tedious; Sentry can automate it, as we will see later.


🧪 Exercises

Exercise 1: Fix the two problems in this collection code: it misses resource loading errors and does not distinguish them from runtime errors:

window.addEventListener('error', (event) => {
    // Write your code here: distinguish runtime and resource loading errors and log each separately
});

Hint: consider the third argument and the property that distinguishes these error types.

Exercise 2: Handle non-Error rejection reasons in this listener so strings such as reject('Network timeout') are recorded correctly:

window.addEventListener('unhandledrejection', (event) => {
    const reason = event.reason;
    // Write your code here: record message and stack for Error objects, otherwise record the string value
});

🎉 You now know how to collect errors! Next, Event Tracking and Data Reporting explains how to collect user behavior data.