Node.js Reference ยท Events and Timers
The error event in Node.js
How the special error event works in Node.js EventEmitter: why a missing listener crashes the process, ERR_UNHANDLED_ERROR, errorMonitor and best practices.
Every event name on an EventEmitter is ordinary except one: 'error'. If an emitter emits 'error' and no listener is registered for it, Node does not silently ignore the event. It throws. When the event carries an Error, that error is thrown; otherwise Node throws a new error describing the problem.
A throw from inside an asynchronous callback, such as a socket or stream event, is an uncaught exception, which ends the process by default. This is why a missing 'error' handler on a stream or server can crash an application that otherwise seems healthy.
stream.on('error', (err) => console.error(err.message));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
How it works
- Unhandled.
emit('error', value)looks for listeners named'error'. If there are none, it throws. Ifvalueis anError, the same object is thrown; if it is anything else, anERR_UNHANDLED_ERRORis thrown whosecontextproperty holds the original value. - Handled. With at least one listener,
emit()calls it like a normal event and returnstrue, and the program continues. errorMonitor.events.errorMonitoris a symbol you can listen to for observing errors, for logging or metrics. Monitor listeners run before regular'error'listeners, and they do not prevent the throw when no real handler exists.- Where it bites. Streams, sockets, servers, child processes and many libraries emit
'error'for failures. Forgetting the handler on any of them turns an I/O failure into a crash. - Choosing the right place. Attach
'error'listeners in the same synchronous block that creates the emitter. Anything emitted before the listener exists is thrown. - Promises.
events.once()rejects when'error'fires, andevents.on()throws it inside the loop, which letstry/catchreplace a listener. - Streams.
stream.pipeline()andfinished()attach error handling for you. Plain.pipe()does not forward errors between streams, so each stream needs its own handler. - Async listeners. A rejected
asynclistener is not an'error'event unlesscaptureRejectionsis on; see captureRejections. - Last resort.
process.on('uncaughtException', ...)can log what slipped through, but the process should still exit afterwards. SeeuncaughtException.
Usage notes
- Emit real
Errorobjects. They carry stack traces; a string or plain object gets wrapped and loses clarity. - One shared handler works. A single logging function can be attached to every emitter you create; it does not have to be a new closure per instance.
- Do not use
'error'for control flow. Use ordinary event names for expected outcomes ('not-found','retry') and keep'error'for failures. - Removing the last handler makes the next error throw again.
removeAllListeners('error')on a long-lived emitter is a bug waiting to happen. - Testing.
emitter.listenerCount('error')tells you whether a handler exists.