Node.js
error event
Learn the 'error' event and error handling.
The error event
In Node.js the "error" event is special. When an EventEmitter emits an "error" event and no listener is registered, Node.js crashes the process and prints a stack trace.
That is why you should always add an error listener on publishers that may produce errors: emitter.on("error", (err) => console.log(err.message));. In emit("error", new Error("Connection lost")) the error object passes to the listener as err. With a listener present, the application keeps running. This is the standard way to propagate and catch errors.
When error is not listened to
When an "error" event is emitted with no listener, Node.js throws an Unhandled 'error' event error and the process stops immediately. This differs from other events: events like "data" are silently ignored if not listened to.
This strict behavior ensures errors never disappear silently. In production a missing error listener crashes the application unexpectedly. That is why adding on("error", ...) is treated as a requirement. The error object's message and stack properties help with debugging.
Exercise Catch the error event
Create an emitter instance. Listen for the "error" event: the listener takes (err) and prints "Caught: " + err.message. Then fire the error with emitter.emit("error", new Error("Connection lost")). Output: Caught: Connection lost.
Show example solution
const { EventEmitter } = require("events");
const emitter = new EventEmitter();
emitter.on("error", (err) => console.log("Caught: " + err.message));
emitter.emit("error", new Error("Connection lost"));
Test yourself
-
Complete the error emit line
emitter.emit("____", new Error("Bağlantı koptu"));
Show answer
emitter.emit("error", new Error("Bağlantı koptu"));
-
Match each concept to its meaning
- error event
- Crashes if not listened
- new Error()
- Creates an error object
- err.message
- Error message
- on("error", ...)
- Adds an error listener
-
What happens if the "error" event is not listened to?
emitter.emit("error", new Error("boom"))
- The Node.js process crashes and throws an error
- The app warns but keeps running
- Nothing happens; it passes silently
- The event is queued forever
Show answer
The Node.js process crashes and throws an error — Node.js crashes if error is not listened to.
Next lesson: Summary - Events