Posted about 1 month 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:

Copy
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:

Copy
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:

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

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Henning Koch
Last edit:
23 days ago
by Dominik Schöler
Keywords:
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