skip to content

Error Reporting & Telemetry

Error reporting catches uncaught errors and rejections, maps minified stacks through private source maps, groups them and sends them on page hide. Interviewers ask how you'd spot a bad release.

on this pageshow

questions

6

For an online tax-filing web app, which failures must the page capture globally, and how do reports reach one pipeline before the tab closes?

level: middleimportance: must knowfreq 52%

answer

  1. four sources, one queue
  2. sync throws versus rejected promises
  3. caught errors are forwarded, not swallowed
  4. failed chunk loads count too
  5. flush the batch when hidden

basics

~20 s

Capture uncaught errors, unhandled promise rejections, errors that render boundaries catch and forward, and failed script or chunk loads; turn each into one report envelope in one in-memory queue, and flush it in small batches when the page becomes hidden.

solid answer

~50 s

Four sources feed one reporter. The window `error` event covers synchronous throws; a promise that rejects with no handler fires `unhandledrejection` instead, so both listeners are needed. Errors a render boundary catches do not reach either listener on their own, so the boundary's report step hands them to the same reporter (or calls `reportError`). Failed script and lazily loaded chunk fetches arrive as load errors or rejected imports, and on an app that ships weekly they are the first sign of a deploy gone wrong. Every source becomes one envelope (release, route template, session id, type, message, stack, breadcrumbs) in one bounded in-memory queue. The queue flushes on a timer while the page is visible and once more when `visibilitychange` reports `hidden`, the last moment the page can reliably act, in batches small enough for the browser to queue.

code

javascript · 32 lines
javascript
const queue = [];        // envelopes from toReport(): scrubbed, stacks truncated
let dropped = 0;
const LIMIT = 48 * 1024; // headroom under the 64 KiB the browser queues for beacons

function enqueue(report) {
  if (queue.length < 50) queue.push(report); else dropped += 1;
}

function flush() {
  const batch = [];
  let size = 0;
  while (queue.length) {
    const next = JSON.stringify(queue[0]).length;
    if (size + next > LIMIT) break;
    batch.push(queue.shift());
    size += next;
  }
  if (batch.length === 0 && dropped === 0) return;
  const body = JSON.stringify({ batch, dropped });
  if (navigator.sendBeacon('/errors', body)) {
    dropped = 0;
  } else {
    queue.unshift(...batch); // not queued by the browser: keep them for the next flush
  }
}

window.addEventListener('error', (e) => enqueue(toReport('error', e.error, e.message)));
window.addEventListener('unhandledrejection', (e) => enqueue(toReport('rejection', e.reason)));
setInterval(flush, 10000);
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') flush();
});

go deeper

for a junior

Recall the two global events: error for synchronous throws and unhandledrejection for promises that reject with no handler, and that errors caught by a render boundary must be forwarded.

for a middle

Explain all four sources, why one envelope and one queue keep scrubbing and sampling in one place, and why the final flush happens when the page becomes hidden rather than on unload.

for a senior

Show the production details: listeners installed before the bundle, chunk-load failures as their own issue after a release, a bounded queue with a dropped count, and deduplication of forwarded errors.

for a principal

Argue the storage trade-off for shared computers, and decide which failure sources page someone versus which only feed dashboards, so the pipeline serves the release decision rather than collecting everything.

## Why one pipeline, not four An **online tax-filing web app** is a long multi-step form: income figures, dependants, deductions, a final submission. When it breaks in the field, nobody files a bug report; the user abandons the return or phones support. The page therefore has to notice failures itself and send them somewhere a team will look. The design question is not "which listener do I add" but **which failure sources exist, and how every one of them ends up in the same queue, in the same shape, sent at a moment the browser will honour**. ## The four sources the page must cover | Source | How it reaches the page | What it misses on its own | |---|---|---| | Uncaught synchronous throw | the window `error` event, with message, file, line, column and the `error` object | anything thrown inside a promise chain | | Promise rejected with no handler | the window `unhandledrejection` event, carrying `reason` | synchronous throws; `reason` may not even be an `Error` | | Error caught by a render boundary | the boundary's own report step | does not reach the two global listeners on its own | | Failed script or lazy chunk load | an `error` event on the script element, or a rejected dynamic import | it is not a script error, so the global `error` handler's message text does not describe it | A few rules turn that table into a design: - **Register both global listeners in a tiny script that runs before the main bundle.** An error thrown while the bundle boots is exactly the one you most need, and a reporter that loads with the bundle misses any error thrown before it installs. - **Give the render boundary a forwarding step.** It calls the same `enqueue` function, or `reportError(error)`, which dispatches an `error` event at the global object as if the error were uncaught. One path means one set of scrubbing, sampling and batching rules. - **Wrap non-`Error` reasons.** A rejection with a string or a plain object has no stack; the reporter wraps it so the envelope keeps one shape. - **Treat chunk-load failures as first-class errors.** After a weekly release, a tab opened the day before may request a chunk that no longer exists. Those failures deserve their own issue, with the chunk URL and both releases, not a place in the noise. - **Deduplicate at the door.** An error a boundary forwards and then rethrows can arrive twice; remembering forwarded error objects in a `WeakSet` drops the second copy. ## One envelope, one queue Every source is normalised into the same envelope before it enters the queue: ```json { "release": "2026.10.06-4f9c2a", "session": "s-7f3c91", "route": "/returns/:returnId/income", "source": "unhandledrejection", "type": "TypeError", "message": "Income total is not a number", "stack": "...", "breadcrumbs": [] } ``` The `release` field lets the error service pick the right build's source maps and compare releases; the `route` is a template, never the raw URL, because a tax app's URLs can carry identifiers. Scrubbing happens here, before the report is queued, so nothing unscrubbed ever sits in memory waiting to leave. The queue is **bounded** (a few dozen reports): a bug firing in a loop must not grow it without limit, so further reports become a dropped-count instead. ## Getting the batch out before the tab closes 1. **While the page is visible**, flush on a timer (every ten seconds or so) or when the queue passes a size threshold. Small, regular sends keep the final flush light. 2. **When `visibilitychange` reports `hidden`**, flush again. Becoming hidden is the last event a page can reliably observe: the user may switch apps on a phone and the browser may later discard the tab without running anything else. `pagehide` is the fallback where `visibilitychange` is not available; `unload` and `beforeunload` are not dependable for this. 3. **Send with a request the browser keeps alive after the page goes**: `navigator.sendBeacon` or `fetch` with `keepalive`. How each behaves, and what its return value proves, is the beacon question's subject; the design consequence here is that the browser queues only a limited amount of such data (about 64 KiB for beacons), so the final batch must be small and the reporter must know what to do when the browser refuses to queue it. ## The trade-off worth stating in the round Should unsent reports be written to storage so the next visit can send them? For a tax app the answer leans **no**: people file on shared family computers and library machines, and a stored report is one more copy of possibly sensitive context left on a device. Keep the queue in memory, flush early and often, and accept losing the occasional report from a tab the browser discarded. A team that does persist reports should persist only scrubbed envelopes with a short expiry.

  • Why should the global listeners be installed by a small script that runs before the main bundle?
    Because the errors that matter most often happen while the bundle boots: a syntax error from a bad build, a missing chunk, a configuration read that throws. A reporter that arrives inside that bundle cannot see its own bundle's failure. A few hundred bytes that register the `error` and `unhandledrejection` listeners and buffer reports in an array close that gap; the full reporter drains the buffer when it loads.
  • Should a tax-filing app write unsent reports to storage so the next visit can send them?
    Usually not. Returns are filed on shared computers, and a stored report is another copy of context about someone's tax return left on the device. Flushing early and often while the page is visible makes the loss small. If the team does persist, it stores only scrubbed envelopes, with a short expiry, and drops them when the user signs out.
  • How do you stop an error from being reported twice when a render boundary forwards it and it also reaches a global listener?
    Mark each forwarded error object, for example in a `WeakSet`, and have `enqueue` skip any object already marked. A `WeakSet` holds no strong reference, so marked errors are still garbage-collected. For values that are not objects, a short-window check on type, message and top frame catches the same repeat.

  • A window error listener also reports promises that reject with no handler.
  • Failed chunk loads after a deploy are network noise, not errors worth reporting.
  • Flushing reports in an unload handler is reliable because it always runs when the tab closes.
  • Sending each report on its own request is fine even when one bug fires in a loop.
  • Writing raw unsent reports to local storage on a shared computer carries no risk.
open as a page

A tax-filing web app loads its bundles from a separate static domain, and every error report reads only 'Script error.'; why, and what must change?

level: middleimportance: should knowfreq 42%

basics

~20 s

The bundles are cross-origin scripts fetched without CORS, so the browser mutes their errors to 'Script error.' with no file, line or error object. Add crossorigin="anonymous" to every script tag and have the static domain send Access-Control-Allow-Origin.

open as a page

A tax-filing web app ships weekly; how would you keep its source maps private yet map every report to the right build, and group reports into issues that survive a release?

level: seniorimportance: should knowfreq 36%

basics

~20 s

Bake a release id into each build and stamp it on every report; upload that build's maps privately, keyed by release, before the deploy goes live. Group by error type, normalised message and top symbolicated in-app frames.

open as a page

In deadline week, a tax-filing web app gets ten times its usual traffic and one bug fires in a loop; how would you sample and cap its error reports?

level: seniorimportance: should knowfreq 33%

basics

~20 s

Decide sampling once per session and put the rate on every report; cap each error group per page and send a count of the repeats; keep submit-step errors at full rate; and let the server change the rate without a release.

open as a page

As lead of a tax-filing web app whose three teams each ship weekly, what release-health gate would you set to catch a bad release, who owns it, and what triggers rollback or a kill switch?

level: principalimportance: should knowfreq 47%

basics

~20 s

Compare each release with the previous one: error-free sessions, new error groups and submit-path failures, tagged by release. A platform team runs the gate; each feature team owns its thresholds; a submit-path breach halts the rollout and flips the switch.

open as a page