Capturing JavaScript Errors

David Cramer

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://browser.sentry-cdn.com/<VERSION>/bundle.min.js"></script>

Configure your DSN:

Sentry.init({ dsn: 'https://<key>@sentry.io/<project>' });

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:

Join the discussionCome work with us
Share on Twitter
Bookmark this page
Ask a questionImprove this Answer

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedin
© 2023 • Sentry is a registered Trademark
of Functional Software, Inc.