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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show 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 snapshot or up.emit() Show 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)


Testing tools like Jasmine Show 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)