Error Monitoring (Sentry-style) — Debugging

Error monitoring (Sentry, for example) sends every error in production (the app people are using) as an event, that is one error report. It holds the message…

Hundreds of ride-hailing passengers report "the app errors when I pay". The help desk staff don't open hundreds of tickets. Reports that are the same get merged: one ticket can say "reported 47 times". Each report also carries a note of what the rider did before the problem appeared.

Error monitoring works the same way, except that the app sends the report itself, without waiting for a user to complain. An error monitoring tool catches errors in the app people are using right now (production). Then the tool sends them automatically to one dashboard (a summary page), complete with the stack trace and context, for example which user and which page. Sentry, Rollbar, Bugsnag and Datadog are examples.

Why you need error monitoring

console.log and DevTools only work on your laptop. You never see an error that happens on a user's phone. Most users don't report it either: they just close the app. For error monitoring, you install an SDK (a small library from the tool) in your app. Every time an error goes uncaught, that SDK sends one event, that is one error report, to the tool's server.

One event holds roughly this:

The Sentry SDK records breadcrumbs automatically: clicks, page changes, fetch requests and console output. For example, this is the trail before a failed login:

navigation  /  →  /login
ui.click    button#login
fetch       POST /api/login  200
error       TypeError: Cannot read property

This trail tells you the login request succeeded (status 200), so the problem is in the code that reads its answer, not on the server.

The error message in this lesson is shortened to Cannot read property, the old form of Chrome's message. Chrome now writes it in full, for example Cannot read properties of undefined (reading 'token').

Fingerprint: the same error becomes one issue

If 500 users hit the same error, you don't want 500 notifications. So the tool calculates a fingerprint (a short text that identifies the error) for each event. Like the merged ticket at the help desk, events with the same fingerprint are merged into one issue, and its count goes up. Sentry uses the stack trace as the fingerprint. When there is no stack trace, Sentry uses the error's type and message. In the exercise the fingerprint is simpler: the first line of error.stack, or error.message when the stack is empty.

For example, these three errors are caught one by one:

# Error Context Fingerprint Result
1 Cannot read property, at login.js:45 u1, env: prod TypeError: Cannot read property new issue, count 1
2 Cannot read property, at login.js:45 u2, env: prod TypeError: Cannot read property same as #1, count becomes 2
3 Network error, at api.js:12 u1, env: staging Error: Network error new issue, count 1

Three reports, but only two issues, and the first issue has a count of 2.

Build a Sentry-style monitor

This is a small monitor like the one in the exercise. capture takes one error report, and the other three methods read the result:

function createMonitor(release) {
  const events = [];
  let nextId = 1;

  function generateFingerprint(error) {
    // the stack trace's first line, or the message when there is no stack
    return error.stack ? error.stack.split('\n')[0] : error.message;
  }

  return {
    capture(error, context) {
      const fingerprint = generateFingerprint(error);
      const existing = events.find((e) => e.fingerprint === fingerprint);
      if (existing) {
        existing.count++; // merged, not a new event
        return existing;
      }
      const event = {
        id: nextId++, message: error.message, fingerprint, release,
        userId: context.userId, url: context.url, tags: context.tags || {},
        timestamp: new Date().toISOString(), count: 1,
      };
      events.push(event);
      return event;
    },
    getEvents: () => events,
    getEventsByTag: (key, value) => events.filter((e) => e.tags[key] === value),
    getTopErrors: (n) => [...events].sort((a, b) => b.count - a.count).slice(0, n),
  };
}

const mon = createMonitor('v1.2.3');
const errLogin = { message: 'Cannot read property', stack: 'TypeError: Cannot read property\n  at login.js:45' };
mon.capture(errLogin, { userId: 'u1', url: '/login', tags: { env: 'prod' } });
mon.capture(errLogin, { userId: 'u2', url: '/login', tags: { env: 'prod' } });
mon.capture(
  { message: 'Network error', stack: 'Error: Network error\n  at api.js:12' },
  { userId: 'u1', tags: { env: 'staging' } }
);

console.log(mon.getEvents().length);                  // 2
console.log(mon.getEvents()[0].count);                // 2
console.log(mon.getEventsByTag('env', 'prod').length); // 1
console.log(mon.getTopErrors(1)[0].message);          // Cannot read property

Set up the real Sentry

In a real app, you use the Sentry SDK. This is how you set it up in a browser app:

import * as Sentry from '@sentry/browser';

Sentry.init({
  dsn: 'https://[email protected]/456', // your project's address in Sentry
  release: '[email protected]',
  environment: 'production',
});

Sentry.setUser({ id: 'u1' });
Sentry.setTag('env', 'prod');

Errors already caught by try/catch

An error you catch yourself with try/catch never reaches the SDK. Report it by hand with Sentry.captureException(error):

try {
  await pay(order);
} catch (error) {
  Sentry.captureException(error); // still sent, with its stack trace
  showMessage('Payment failed, please try again.');
}

For something that isn't an error, use Sentry.captureMessage('expired coupon used'). To add a trail entry (a breadcrumb) of your own, use Sentry.addBreadcrumb({ category: 'checkout', message: 'chose QR payment', level: 'info' }).

⚠️ What makes the dashboard numbers lie

TL;DR: Error monitoring (Sentry, for example) sends every error in production (the app people are using) as an event, that is one error report. It holds the message, stack trace, release (version), user, tags (labels) and breadcrumbs (the trail of clicks, navigation and fetches before the error). Events with the same fingerprint (a short text that identifies the error) are merged into one issue (one problem on the dashboard), and its count (number of reports) goes up, so 3 reports can become 2 issues. In the exercise, the fingerprint is the first line of error.stack or error.message, getEventsByTag filters on tags[key] === value, and getTopErrors(n) sorts a copy of the event list from the biggest count. In a real app, call Sentry.init with release and environment (production or staging). Report errors you catch yourself with Sentry.captureException(error).

⚡ You never see errors on users' phones

Meaning: console.log and DevTools only work on your laptop. For error monitoring, Sentry for example, you install an SDK (a small library from the tool) in your app. Every uncaught error is sent automatically as an event (one error report): message, stack trace, release (the app version), user, tags (labels) and breadcrumbs (the trail before the error).

⚡ Breadcrumbs: the trail before the error

Write:

navigation  /  →  /login
ui.click    button#login
fetch       POST /api/login  200
error       TypeError: Cannot read property

Meaning: The SDK records this trail automatically: a page change, a click, then the login request. The login request succeeded (status 200), so the problem is in the code that reads its answer, not on the server.

⚡ Same fingerprint, one issue

Guess first: every error has a fingerprint (a short text that identifies the error), and errors with the same fingerprint are merged into one issue. Three reports come in, two of them the same login error. How many issues on the dashboard?

Two. The two login errors are merged into one issue, and its count goes up to 2.

Meaning: 500 users hit by the same error don't make 500 notifications, just one issue with a count (number of reports) of 500.

⚡ Errors you catch yourself

Write:

try {
  await pay(order);
} catch (error) {
  Sentry.captureException(error); // still sent, with its stack trace
  showMessage('Payment failed, please try again.');
}
Guess first: if the catch only does console.log(error), does the error appear on the dashboard?

No. An error you catch yourself never reaches the SDK. The dashboard stays clean while users fail to pay.

Meaning: Report it with Sentry.captureException(error) inside the catch, as in this code.

What you will learn