error event
- Node.js course
- Intermediate
- Lesson 5/116
- 5 min
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.
Practice 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.
Starter code
// Create an emitter instance
// write here
// Listen for the "error" event
// write here
// Fire the error event
// write hereSample 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"));Expected output
Yakalandı: Bağlantı koptu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the error emit line
emitter.emit("____", new Error("Bağlantı koptu"));
emitter.emit("error", new Error("Bağlantı koptu"));
Explanation: The error event name is emitted.
2 Match each concept to its meaning
| Term | Meaning |
|---|---|
error event |
Crashes if not listened |
new Error() |
Creates an error object |
err.message |
Error message |
on("error", ...) |
Adds an error listener |
3 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 Correct answer
- The app warns but keeps running
- Nothing happens; it passes silently
- The event is queued forever
Explanation: Node.js crashes if error is not listened to.