JavaScript

Capturing JavaScript Errors

The Problem

You have a single page JavaScript application, and unlike your API server, the client-side application doesn't generate error logs.

The Solution

A good starter practice is to instrument your application using try...catch statements. This allows you to gracefully handle the error and show a message to the user:

<div id="page"></div>

<script>
try {
    renderPage()
} catch (err) {
    document.getElementById('page').innerHTML = 'An error occurred: ' + err.message;
}
</script>

Reporting JavaScript Errors

Now, while this pattern will help you create a better user experience, it still doesn't inform you about these kinds of events. A minor change can be made to greatly improve this abstraction:

<script>
function logError(err) {
    // send the error to our reporting server
    $.ajax({
        url: 'http://example.com/report-js-error',
        method: 'POST',
        data: {
            'message': err.message,
            'stack': err.stack,
        }
    });
    // for debug purposes, also capture it to console
    console && console.log(err);
}

try {
    renderPage()
} catch(err) {
    logError(err);
    document.getElementById('page').innerHTML = (
        'An error occurred. Dont worry though, weve ' +
        'been alerted and are working on a solution'
    );
}
</script>

Uncaught Exceptions

We're able to gracefully handle page rendering errors, but what about the rest of our application? This is where Sentry fits into place. Sentry takes care of automatically instrumenting the JavaScript stack and sends errors to the reporting server. By using Sentry you can avoid the try...catch pattern.

Integrating the JavaScript SDK is just a few lines of code:

<script src="https://cdn.ravenjs.com/3.11.0/raven.min.js"></script>
<script>
Raven.config('https://<key>@sentry.io/<project>').install()
</script>

That's it! Sentry takes care of the problem and gets out of your way.

Further Reading

If you're looking to get a deeper understanding of how JavaScript error reporting works, take a look at the following articles:

The Experts
David Cramer
Don't just log bugs, fix them with Sentry.
Think we can improve something on this page? Let us know!