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