Error Events Throw Without A Listener

Emitting error without an error listener throws immediately instead of being dropped, so every EventEmitter should register its error handler first.

JavascriptResilience

Code

javascriptsnippet
19 lines
import { EventEmitter } from 'node:events';

// 'error' is special: with no 'error' listener, emit throws instead of ignoring
const jobs = new EventEmitter();

jobs.on('done', (name) => console.log('finished:', name));
jobs.emit('done', 'upload'); // normal events without listeners are dropped silently
jobs.emit('never-registered');

// The moment an 'error' event is emitted with no listener, the throw happens here
try {
  jobs.emit('error', new Error('boom'));
} catch (err) {
  console.log('uncaught:', err.message);
}

// Registering an 'error' listener converts the crash into a normal callback
jobs.on('error', (err) => console.log('handled:', err.message));
jobs.emit('error', new Error('disk full'));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

finished: upload
uncaught: boom
handled: disk full

What the demo throws

A done event with a registered listener prints finished: upload. The next line emits never-registered with no listener and nothing happens, because ordinary events without listeners are dropped silently by EventEmitter.

error is the exception: emitting it with no error listener throws right at the emit call, caught here in a try block and printed as uncaught: boom. Registering an error handler afterwards converts the same emission into a normal callback, printing handled: disk full.

Caveats and details

  • The throw happens synchronously where emit is called.
  • Register the error listener before any emit that can fail.

Interactive Tools for This Topic

FAQ

Why does emitting error throw without a listener?
EventEmitter treats error specially: an unhandled error event is rethrown at the emit call site instead of being ignored, which the try block around the first emit captures.