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