Error handling in DOM event listeners

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

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.

Henning Koch Over 3 years ago