Read more

Error handling in DOM event listeners

Henning Koch
July 02, 2020Software engineer at makandra GmbH

When an event listener on a DOM element throws an error, that error will be silenced and not interrupt your program.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

In particular, other event listeners will still be called even after a previous listener threw an error. Also the function that emitted the event (like element.dispatchEvent() Show archive.org snapshot or up.emit() Show archive.org snapshot ) will not throw either.

In the following example two handlers are listening to the foo event. The first handler crashes, the second handler still runs:

document.addEventListener("foo", function(event) {
  throw new Error("Event handler crashed")
})

document.addEventListener("foo", function(event) {
  console.log("I will run even though the previous handler crashed")
})

let fooEvent = new CustomEvent("foo")
document.dispatchEvent(fooEvent) // will not throw
console.log("I will run because dispatchEvent didn't throw")

The browser will still print the exception message and trace to the error log:

Uncaught Error: Event handler crashed

If you would like to access errors thrown from event handlers, you may listen to the error event on window. It will be emitted for all uncaught errors in the current JavaScript VM:

window.addEventListener('error', function(event) {
  console.log("Got an uncaught error: ", event.error)
})

Tip

Testing tools like Jasmine Show archive.org snapshot might also listen to the error event and fail your test if any uncaught exception is observed. In Jasmine you may use jasmine.spyOnGlobalErrorsAsync() to make assertions on the unhandled error.

Posted by Henning Koch to makandra dev (2020-07-02 14:10)