Sentry Answers>JavaScript>

Capturing JavaScript Errors

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:

Click to Copy
<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:

Click to Copy
<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:

Click to Copy
<script src="https://browser.sentry-cdn.com/<VERSION>/bundle.min.js"></script>

Configure your DSN:

Click to Copy
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:

  • ResourcesImprove Web Browser Performance - Find the JavaScript code causing slowdowns
  • SentryJavascript Error Monitoring & Tracing
  • ResourcesJavaScript Frontend Error Monitoring 101
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

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