Home > Software design >  Event handling in JavaScript: how should I handle errors from DOM events?
Event handling in JavaScript: how should I handle errors from DOM events?

Time:09-26

I have the following code:

const button = document.querySelector("button");

button.addEventListener("click", function() {
  throw Error("Can't touch this button!");
});

Here we throw an exception as soon as the button is clicked. How do we catch it? It is obvious that this pattern does not work

const button = document.querySelector("button");

try {
  button.addEventListener("click", function() {
    throw Error("Can't touch this button!");
  });
} catch (error) {
  console.error(error.message);
}

I wonder in a browser environment what the common ways are to handle errors like this?

CodePudding user response:

In a browser context you can register a handler for the error event on window:

window.onerror = function (e) {
    console.log("custom error handler kicked in");
    return true; // Prevent default error handler
};

It is important that this code does not itself trigger an error, or the handler will be called again, and again...

  • Related