Skip to content

Instantly share code, notes, and snippets.

@unional
Last active November 17, 2017 00:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unional/68c6a9477b2f128d50c9388a5548a885 to your computer and use it in GitHub Desktop.
Save unional/68c6a9477b2f128d50c9388a5548a885 to your computer and use it in GitHub Desktop.
Error thrown in event listener affects emit code
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()
@unional
Copy link
Author

unional commented Oct 28, 2017

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.

@unional
Copy link
Author

unional commented Oct 28, 2017

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