Advertisement
Intermediate Node.js, Events & EventEmitter

What happens when an EventEmitter emits an event that has an 'error' listener versus one that doesn't?

Short answer

The 'error' event is treated specially by EventEmitter -- if it's emitted and there is no registered listener for it, Node.js throws the error and, by default, crashes the process, unlike every other event type which simply does nothing (silently) if no listener is attached…

Save Node.js mock interview
Advertisement
AModel answer
The 'error' event is treated specially by EventEmitter -- if it's emitted and there is no registered listener for it, Node.js throws the error and, by default, crashes the process, unlike every other event type which simply does nothing (silently) if no listener is attached; this special behavior exists specifically to prevent errors from being silently swallowed and ignored, forcing every EventEmitter-based component to have explicit error handling.
const emitter = new EventEmitter();

// No listener for 'error' -- this crashes the process
emitter.emit('error', new Error('Something went wrong'));

// With a listener attached, the error is handled gracefully instead
emitter.on('error', (err) => console.error('Handled:', err.message));
emitter.emit('error', new Error('Something went wrong'));
Real-world example
A team's custom database-connection wrapper class (extending EventEmitter) crashed the entire application in production the first time a connection error occurred, because no code anywhere had attached an 'error' listener to it -- adding that listener prevented the crash and let the error be logged and handled gracefully instead.
Likely follow-ups
  • Why did Node.js's designers choose this special-case crash behavior specifically for the 'error' event rather than every event type?
  • How does this relate to and differ from the unhandled promise rejection behavior discussed for async code?
Related topics