Error Events and Error Handling
You'll learn how the special 'error' event is handled differently from other events and why it's critical for process stability in Node.js.
The Error Event Convention
Most event emitters follow a common pattern: if an event is emitted but no listener exists for it, nothing happens—the event is silently ignored. The 'error' event is special. If an emitter emits an 'error' event and no listener is registered for it, the default behavior is to throw the error, which can crash a Node.js process.
Think of it like a fire alarm in a building: if there's smoke (an error) but nobody's listening for the alarm, the system has to do something drastic—stop everything and evacuate (crash).
Why This Matters
const EventEmitter = require('events');
const emitter = new EventEmitter();
// Dangerous: no error listener registered
emitter.emit('error', new Error('Something went wrong!'));
// This will throw and crash the process!
To handle errors safely, always register an 'error' listener:
const emitter = new EventEmitter();
// Safe: error listener in place
emitter.on('error', (err) => {
console.error('Caught error:', err.message);
});
emitter.emit('error', new Error('Something went wrong!'));
// Logs the error, process continues running
Best Practice
For any EventEmitter—especially in long-running Node.js servers—register an error handler early. This prevents unexpected crashes and gives you control over error recovery, logging, and retry logic.
Key Takeaway:
The 'error' event is special: if emitted without a listener, it throws and can crash your Node.js process. Always register an error handler to prevent unexpected termination.