Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
Questions about handling errors from DOM events

I read this article from Ben Nadel about leveraging capturing phase to capture errors from img element onload event since he mentioned that error event doesn't bubble up.

So what he did was

    refs.body.addEventListener(
            "error",
            handleErrorCapture,
            // According to the DOM (Document Object Model) specification, the ERROR and
            // LOAD events for Images do not BUBBLE up through the DOM tree. As such, we
            // have to use the CAPTURE phase, which starts at the top of the DOM and
            // descends down into the DOM toward the target element.
            true
        );

My first question is, why didn't he consider using window.onerror to capture the errors? It seems like it would be much more easier.

Then I tried the same approach with a button that when clicked more than 5 times it would throw an error in its onclick handler. And then I attached a error event listener on document.body to capture the events in the capturing phase of event propagation, just like what the article did.

const btn = document.querySelector("#btn");

btn.addEventListener("click", () => {
  btn.textContent = Number(btn.textContent) + 1;
  if (Number(btn.textContent) > 5) {
    throw new Error("lol"); // 💣
  }
});

document.body.addEventListener(
  "error",
  function (event) {
    // 👇 this doesn't work
    console.log("Got an uncaught error: in body", event.error);
  },
  true
);

However it doesn't seem to be able to capture the error events. So my second question is why this is not working?

Finally if I attached a error listener on window then it would be working.

You can can try the demo here https://codesandbox.io/s/dom-error-handling-oz66c?file=/src/index.js:254-424

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda