How do we track Javascript errors? Do the existing tools actually work?

It's difficult to get a stack trace from errors that happen "in the wild" right now, because the Error object isn't available to window.onerror.

window.onerror = function(message, file, line) { }

There is also a new error event, but this event doesn't expose the Error object (yet).

window.addEventListener('error', function(errorEvent) { })

Soon, window.onerror will get a fifth parameter containing the Error object, and you can probably use stacktrace.js to grab a stack trace during window.onerror.

<script src="stacktrace.js"></script>
<script>
window.onerror = function(message, file, line, column, error) {
    try {
        var trace = printStackTrace({e: error}).join('\n');
        var url = 'http://yourserver.com/?jserror=' + encodeURIComponent(trace);
        var p = new printStackTrace.implementation();
        var xhr = p.createXMLHTTPObject();

        xhr.open('GET', url, true);
        xhr.send(null);
    } catch (e) { }
}
</script>

At some point the Error API will probably be standardized, but for now, each implementation is different, so it's probably smart to use something like stacktracejs to grab the stack trace, since doing so requires a separate code path for each browser.


I'm the cofounder of TrackJS, mentioned above. You are correct, sometimes getting the stack traces requires a little bit of work. At some level, async functions have to be wrapped in a try/catch block--but we do this automatically!

In TrackJS 2.0+, any function you pass into a callback (addEventListener, setTimeout, etc) will be automatically wrapped in a try/catch. We've found that we can catch nearly everything with this.

For the few things that we might now, you can always try/catch it yourself. We provide some helpful wrappers to help, for example:

function foo() {
  // does stuff that might blow up
}

trackJs.watch(foo);