Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
Event handling in JavaScript: how should I handle errors from DOM events?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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...

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!