← Back to JavaScript, page 10

javascript-0190 · Hard senior

How would you design a client-side error monitoring library that captures errors, groups them, and does not hurt the page?

Capture window error events, unhandledrejection, resource errors, and handled errors from a captureException API, normalize them into a payload with stack, release, and context, scrub personal data, de-duplicate and sample, send in batches with sendBeacon or fetch keepalive, and resolve stacks with source maps on the server. The library must never throw, loop, or slow the app.

Full answer

Goals: find real user-facing errors quickly, group them into issues, give enough context to fix them, and add almost no cost or risk to the page.

Capture:

  1. window.addEventListener('error', ...) for uncaught errors and, with the capture flag, for failed resource loads (images, scripts). Cross-origin scripts give only "Script error." unless they use CORS (crossorigin attribute and the right headers).
  2. window.addEventListener('unhandledrejection', ...), whose event.reason may not be an Error (it can be a string or object), so normalize it.
  3. A manual API captureException(error, context) for handled errors, plus integration with frameworks (error boundaries) and wrapping of fetch and XHR to record failed requests.
  4. Breadcrumbs: a small ring buffer of recent events (clicks, navigations, network calls, console messages) to show what led to the error.

Payload: message, error type, stack frames (parsed from error.stack, which differs between engines), release and environment, URL (scrub tokens), user agent, a session id, an anonymous or hashed user id, and error.cause chain. Add custom tags.

Processing in the client:

  • Dedupe: fingerprint by type, message with numbers removed, and top frame. Send the first, then count repeats and rate-limit per fingerprint to survive error loops.
  • Sample: sampling rate for noisy apps, and always keep new fingerprints.
  • Ignore known noise: browser extension errors, ResizeObserver loop warnings, and aborted requests (AbortError).
  • Guard against recursion: if the reporter itself fails, do not report that failure.
  • Scrub personal data: remove query strings with tokens, form values, and request bodies by default, and offer a user-controlled filter before sending.

Delivery: same approach as analytics: batch, sendBeacon or fetch with keepalive on page hide, retry with backoff, bounded queue, and an endpoint that is not blocked by the page's CSP.

Server and workflow: upload source maps for each release (not public in production), resolve minified stacks, group issues, link to releases and commits, alert on regressions, and track the crash-free sessions rate.

Trade-offs: more context helps debugging but increases privacy risk and payload size. Choose conservative defaults with opt-in for more.

javascript
function createMonitor({ send, release, maxBreadcrumbs = 3, maxPerFingerprint = 2 }) {
  const breadcrumbs = [];
  const counts = new Map();
  const outbox = [];
  let reporting = false;

  const scrub = (text) => String(text).replace(/([?&](?:token|key|password)=)[^&\s]+/gi, '$1[removed]');
  const normalize = (input) => {
    if (input instanceof Error) return input;
    const error = new Error(typeof input === 'string' ? input : 'Non-error value: ' + JSON.stringify(input));
    error.name = 'NonErrorRejection';
    return error;
  };
  const topFrame = (error) => (error.stack?.split('\n').find((line) => line.trim().startsWith('at ')) ?? 'no-frame').replace(/\(.*[\\/]/, '(').replace(/:\d+:\d+\)?/, '');
  const fingerprint = (error) => [error.name, String(error.message).replace(/\d+/g, 'N'), topFrame(error)].join('|');

  const chain = (error) => {
    const out = [];
    for (let e = error, i = 0; e && i < 5; e = e.cause, i++) out.push(`${e.name}: ${scrub(e.message)}`);
    return out;
  };

  return {
    breadcrumb(text) {
      breadcrumbs.push(scrub(text));
      if (breadcrumbs.length > maxBreadcrumbs) breadcrumbs.shift();
    },
    capture(input, context = {}) {
      if (reporting) return;
      reporting = true;
      try {
        const error = normalize(input);
        if (error.name === 'AbortError') return 'ignored';
        const key = fingerprint(error);
        const seen = (counts.get(key) ?? 0) + 1;
        counts.set(key, seen);
        if (seen > maxPerFingerprint) return 'rate limited';
        const event = { release, type: error.name, chain: chain(error), breadcrumbs: [...breadcrumbs], context, fingerprint: key.split('|').slice(0, 2).join('|') };
        outbox.push(event);
        send(event);
        return 'sent';
      } catch {
        return 'monitor failed silently';
      } finally {
        reporting = false;
      }
    },
    counts: () => Object.fromEntries([...counts].map(([k, v]) => [k.split('|').slice(0, 2).join('|'), v])),
    outbox,
  };
}

const sent = [];
const monitor = createMonitor({ send: (event) => sent.push(event), release: 'web@1.4.2' });

monitor.breadcrumb('click #save');
monitor.breadcrumb('POST /api/save?token=abc123');
monitor.breadcrumb('navigate /settings');
monitor.breadcrumb('click #logout');

const fail = (id) => { throw new TypeError(`Cannot read user ${id}`); };
const results = [];
for (const id of [101, 102, 103]) {
  try { fail(id); } catch (error) { results.push(monitor.capture(error, { page: '/settings' })); }
}
console.log('same error with different numbers:', results, monitor.counts());

console.log('string rejection:', monitor.capture('timeout while saving'));
console.log('object rejection:', monitor.capture({ code: 42 }), '|', sent.at(-1).type);
console.log('abort ignored:', monitor.capture(Object.assign(new Error('x'), { name: 'AbortError' })));

const wrapped = new Error('Could not save settings', { cause: new RangeError('payload too large?key=SECRET') });
monitor.capture(wrapped);
const last = sent.at(-1);
console.log('chain with scrubbed cause:', last.chain);
console.log('release and breadcrumbs:', last.release, last.breadcrumbs);
console.log('events sent:', sent.length);

Run with Node.js v24.22.1 as js-190.js; two runs gave identical output. Output: same error with different numbers: [ 'sent', 'sent', 'rate limited' ] { 'TypeError|Cannot read user N': 3 } string rejection: sent object rejection: sent | NonErrorRejection abort ignored: ignored chain with scrubbed cause: [ 'Error: Could not save settings', 'RangeError: payload too large?key=[removed]' ] release and breadcrumbs: web@1.4.2 [ 'POST /api/save?token=[removed]', 'navigate /settings', 'click #logout' ] events sent: 5

Key points

  • Capture error, unhandledrejection, resource errors, and a manual captureException; normalize non-Error reasons.
  • Add release, breadcrumbs, and cause chains; scrub personal data.
  • Dedupe with a fingerprint, sample, rate-limit, and ignore known noise.
  • Never throw or recurse; deliver in batches with beacon or keepalive.
  • Resolve stacks with source maps on the server, grouped by release.

Common mistakes

  • Reporting errors from inside the error reporter, which can loop.
  • Sending every repeat of an error that fires in a loop.
  • Sending tokens, form values, or personal data in URLs and breadcrumbs.
  • Ignoring unhandled rejections with non-Error reasons.

Follow-ups

  • How do source maps resolve a minified stack?
  • Why does a cross-origin script give only "Script error."?
  • How would you measure the cost of the monitor?

Tips

  • Cover capture, enrich, filter, deliver, and analyze as five steps.
  • Mention privacy and rate limiting early.
  • Say the library must never throw.