Posted 3 months ago. Visible to the public. Repeats.

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() or up.emit()) 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) })

Note that testing tools like Jasmine might also listen to the error event and fail your test if any uncaught exception is observed.

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Henning Koch
Last edit:
3 months ago
by Dominik Schöler
raise, exception
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more