Last active
November 17, 2017 00:18
-
-
Save unional/68c6a9477b2f128d50c9388a5548a885 to your computer and use it in GitHub Desktop.
Error thrown in event listener affects emit code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const EventEmitter = require('events') | |
const emitter = new Eventemitter() | |
function shouldNotThrow() { | |
try { | |
emitter.emit('x') | |
} | |
catch { | |
// unfortunately, error is thrown | |
} | |
} | |
emitter.on('x', () => { throw new Error('thrown') }) | |
shouldNotThrow() |
One way to mitigate this is to wrap the listener.
class FireAndForgetEmitter extends EventEmitter {
on(event, listener) {
const wrappedListener = (...args) => {
try {
listener(...args)
}
catch (err) {
this.emit('error', err)
}
}
}
super.on(event, wrappedListener)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This behavior surprised me.
It makes sense (in JavaScript) but at the same time doesn't make sense.
I would assume event to be fire-and-forget.
It is not the case there because JavaScript is single threaded.