Skip to content

Instantly share code, notes, and snippets.

@rumkin
Last active May 27, 2020 16:12
Show Gist options
  • Save rumkin/aa8355367d553abc5c5c540f99f43ec7 to your computer and use it in GitHub Desktop.
Save rumkin/aa8355367d553abc5c5c540f99f43ec7 to your computer and use it in GitHub Desktop.
EventTarget is an error teleporter

EventTarget is an error teleporter

Here is an exmaple of the code which will teleport Error from the place it should be handled to the place it whouldn't occur.

const target = new EventTarget()

target.addEventListener('event', () => {
  throw new Error('Some error')
})

try {
  target.dispatchEvent(new CustomEvent("event"))
  console.log("✅")
} catch (_) {
  console.log("❌") // 👈 This is where we get with EventTarget
}

How it could be fixed? It could fixed with event source which produces async iterator for reading events:

const source = new EventSource()

for await (const event of source.listen("event")) {
  throw new Error('Some error') // Now error should be handled in-place
}

// Somewhere in the code...
try {
  source.dispatchEvent(new CustomEvent("event"))
  console.log("✅") // 👈 This is where we get with EventSource
} catch (_) {
  console.log("❌")
}

© Rumkin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment