Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda