❯ehsan.blog
~/blog/your-error-handler-cant-see-broken-images — zsh
❯cat your-error-handler-cant-see-broken-images.md

Your error handler can't see broken images

·8 min read

Your error handler can't see broken images — article card for a post by Ehsan Shahid

Your error handler probably can’t see broken images, and nothing will tell you that. Most front-end error tracking starts with one line, and it is almost always this one:

js
window.addEventListener("error", (event) => {
  report(event.error)
})

It works. Throw a TypeError in a click handler and it shows up. So you ship it, and for months it quietly does its job.

Then somebody’s profile picture is a grey box in production, and nothing about it is in your logs. Not a warning. Not an entry. The image asked the server for a file, the server said 404, and your error handler — the one you installed specifically so you would hear about problems — never made a sound.

The fix is one argument. What makes it worth a whole post is what that one argument does next: it starts handing your logger a second kind of event that looks nothing like the first, and your reporting line turns it into undefined.

Two things are called “error” and they are not the same thing

The browser fires an error event for two completely unrelated situations:

  1. An uncaught exception. Some code threw and nobody caught it.
  2. A resource failed to load. An <img>, <script> or stylesheet asked for a file and did not get it.

The first one bubbles up to window. The second one does not. It fires on the element itself and stops there, so a normal listener on window never sees it. This is not a quirk of one browser — it is in the spec, and MDN’s page on the error event says so plainly for element-level failures.

I tested this rather than trusting my memory. A page with a listener on window, a broken image, and a real thrown error:

js
window.addEventListener("error", (e) => {
  const tag = e.target && e.target.tagName
  if (tag === "IMG") sawImage = true
  else sawException = true
})

const img = document.createElement("img")
img.src = "/does-not-exist-404.png"
document.body.appendChild(img)

setTimeout(() => { throw new TypeError("boom from test") }, 50)

The result, in Chromium:

plaintext
sawImage:     false
sawException: true

The thrown error arrived. The broken image did not. And window.onerror = fn, the older property-style version, does not see it either — I checked that in the same run.

The fix is one extra argument

Resource errors never bubble up, but they do travel down first. Every event goes down from window to the element before it comes back up, and you can ask to be told on the way down instead. That is the capture phase, and it is the third argument to addEventListener:

flowchart LR
    W1["window<br/>⬇ capture"] --> D1["document"] --> T["&lt;img&gt;<br/>target"]
    T --> D2["document"] --> W2["window<br/>⬆ bubble"]
    W1 -.- C["capture: true<br/>✅ sees both"]
    W2 -.- B["default listener<br/>❌ resource errors<br/>never get here"]

An uncaught exception makes the whole round trip, so a default listener catches it on the way back up. A resource failure stops at the target and never starts the return journey, so the only chance to see it is on the way down.

js
window.addEventListener("error", handler, true)
//                                        ^^^^ capture

Same page, same broken image, one word different:

plaintext
sawImage:     true
sawException: true

Now you see both. This part is documented, and it is the fix that usually gets posted. The problem is what it does to the handler you already wrote.

Your handler now gets an event it was never written for

Look again at the line everybody starts with: report(event.error). That assumes the event has an error. An uncaught exception does. A failed image does not — it is not even the same class of object.

I printed the shape of both events from the same capture-phase listener:

plaintext
uncaught exception   →  ErrorEvent   error: present   message: "Uncaught TypeError: boom from test"
broken image         →  Event        error: absent    message: undefined

The resource failure is a plain Event. There is no error property on it at all, and no message either. So the moment you add true and start receiving these, your reporting line starts sending undefined — and it does it for every broken asset on the page.

Here is a page with three broken resources and one genuine exception, run through the naive handler:

js
window.addEventListener("error", (e) => {
  naive.push({
    message: String(e.message),
    viaErrorDotMessage: String(e.error && e.error.message),
  })
}, true)

The four events it collected:

plaintext
{ message: "undefined",                          viaErrorDotMessage: "undefined" }
{ message: "undefined",                          viaErrorDotMessage: "undefined" }
{ message: "undefined",                          viaErrorDotMessage: "undefined" }
{ message: "Uncaught TypeError: a real exception", viaErrorDotMessage: "a real exception" }

Three useless lines and one good one. The broken <img>, the broken <script> and the broken stylesheet all landed as undefined.

This is worse than the bug you were fixing. Before, you were missing information. Now you are producing noise that looks like information — and noise is what makes people stop reading a log. A page with a dozen broken thumbnails writes a dozen undefined errors, and the real exception underneath them gets scrolled past.

Tell the two apart before you log

The check is small: a real exception has an error, a failed resource has a target with a tag name.

js
window.addEventListener("error", (event) => {
  // 1. A genuine uncaught exception.
  if (event.error != null) {
    report({ kind: "exception", error: event.error })
    return
  }

  // 2. A resource that failed to load.
  const el = event.target
  if (el && el.tagName) {
    report({
      kind: "resource",
      tag: el.tagName.toLowerCase(),
      url: el.src || el.href,
    })
    return
  }

  // 3. Anything else — cross-origin scripts land here, censored to
  //    "Script error." with no error object attached.
  report({ kind: "unknown", message: event.message })
}, true)

Note the order. event.error is checked first, because that is the only test that positively identifies a real exception. And it is != null, not just truthy, so somebody doing throw 0 or throw "" does not get misfiled as a resource failure.

That third branch is not padding, either. I served a throwing script from a second origin with no CORS headers and watched what arrived:

plaintext
ctor: "ErrorEvent"   message: "Script error."   error: null   target: window

The browser censors cross-origin failures on purpose — you get the string "Script error." and nothing else, because the details could leak information from another site. Note that error is null there, not undefined. That is the second reason the check is != null: one comparison covers both the missing property on a resource event and the deliberately nulled one here. A truthy check would work too, but != null is the one that says what it means.

The same four events, through that handler:

plaintext
{ kind: "resource",  tag: "img",    url: "nope-img.png" }
{ kind: "resource",  tag: "link",   url: "nope-style.css" }
{ kind: "resource",  tag: "script", url: "nope-script.js" }
{ kind: "exception", message: "a real exception" }

Every line now says something true. The broken assets are identified by tag and URL, which is what you actually need to fix them, and the exception is still an exception.

If those lines then go into a JSON logger, there is a separate trap waiting right behind this one: JSON.stringify(err) on an Error gives you {}, which I wrote up in why JSON.stringify(error) prints {} in your logs. Catching the error and then logging nothing useful about it is a short trip.

One detail worth keeping: log the resource failures at a lower level than the exceptions — warn rather than error. A missing avatar and a crashed checkout button are not the same emergency, and once they share a severity you lose the ability to alert on one without the other.

Two more things this handler needs before it is safe to leave running, both easy to forget:

Do not let it recurse. If report() itself throws, that throw is an uncaught exception, which fires the handler, which calls report() again. A single flag is enough:

js
let capturing = false
const guard = (fn) => {
  if (capturing) return
  capturing = true
  try { fn() } catch { /* a logger that throws is worse than no logger */ }
  finally { capturing = false }
}

Do not install it twice. Under React’s StrictMode, or after a hot reload, the setup code can run more than once, and every duplicate listener means another copy of every line. Keep the uninstall function around and return it early if it already exists. If you are sending these to a server rather than the console, the same reasoning about batching and back-pressure applies as in how client logs reach your terminal.

The part that generalises

The capture-phase argument is the famous half of this, and on its own it is a trap. Turning on a new source of events without checking what those events look like is how you end up with a monitoring system that is technically catching more and telling you less.

Whenever one handler is subscribed to two different producers, the useful question is not “am I receiving everything?” It is “does everything I receive actually fit the shape I wrote this for?” Here the answer was no, and the browser gave no warning — undefined is a perfectly valid thing to log.

The verification is cheap, too. Every claim above came out of a page I loaded in a browser and read the output from, which took a few minutes and settled three things I would otherwise have half-remembered. Worth doing before the logs are the only thing you have left to look at.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.