Error events and handling help your program catch problems and respond without crashing. It keeps your app running smoothly and lets you fix or report errors.
Error events and handling in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
emitter.on('error', (err) => {
// handle the error here
});Use the 'error' event on objects that emit events, like streams or servers.
Always handle 'error' events to avoid your program crashing.
Examples
Node.js
const fs = require('fs'); const stream = fs.createReadStream('file.txt'); stream.on('error', (err) => { console.error('Error reading file:', err.message); });
Node.js
const net = require('net'); const server = net.createServer(); server.on('error', (err) => { console.error('Server error:', err.message); });
Sample Program
This program tries to read a file that does not exist. Instead of crashing, it catches the error and prints a message.
Node.js
import { createReadStream } from 'node:fs'; const stream = createReadStream('missing.txt'); stream.on('error', (err) => { console.log(`Caught error: ${err.message}`); });
Important Notes
Always add an 'error' event listener on streams and servers to prevent crashes.
Errors provide useful info in the error object, like message and code.
Use try-catch blocks for synchronous code, but use 'error' events for asynchronous event emitters.
Summary
Error events let you catch problems in asynchronous code.
Always handle 'error' events on event emitters like streams and servers.
Handling errors keeps your app stable and user-friendly.
Practice
1. What is the main purpose of handling
error events in Node.js event emitters?easy
Solution
Step 1: Understand the role of error events
Error events in Node.js are emitted when something goes wrong in asynchronous operations.Step 2: Identify the purpose of handling errors
Handling these events allows the program to respond properly, avoiding crashes and improving stability.Final Answer:
To catch and respond to problems in asynchronous code -> Option CQuick Check:
Error events catch async problems = B [OK]
Hint: Error events catch async problems to keep app stable [OK]
Common Mistakes:
- Thinking error events improve speed
- Assuming error events restart servers automatically
- Confusing error events with logging user actions
2. Which of the following is the correct way to listen for an
error event on a Node.js stream named myStream?easy
Solution
Step 1: Recall the event listener syntax in Node.js
Node.js uses theonmethod to listen to events on event emitters like streams.Step 2: Verify the correct method and parameters
The correct syntax ismyStream.on('error', callback)where callback receives the error object.Final Answer:
myStream.on('error', (err) => { console.error(err); }); -> Option DQuick Check:
Use .on('error', callback) to handle errors [OK]
Hint: Use .on('error', callback) to handle errors [OK]
Common Mistakes:
- Using .error() instead of .on()
- Using .listen() or .catch() which don't exist
- Missing the event name string 'error'
3. Consider this code snippet:
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('error', (err) => { console.log('Error caught:', err.message); });
emitter.emit('error', new Error('Oops!'));
What will be printed to the console?medium
Solution
Step 1: Analyze the event listener setup
The code sets a listener for the 'error' event that logs the error message prefixed by 'Error caught:'.Step 2: Understand the emitted event
The emitter emits an 'error' event with an Error object having message 'Oops!'. The listener runs and logs the message.Final Answer:
Error caught: Oops! -> Option AQuick Check:
Handled error event logs message = A [OK]
Hint: If error event has listener, it logs message [OK]
Common Mistakes:
- Expecting unhandled error crash
- Confusing error object with string output
- Thinking no output occurs without console.log
4. What is wrong with this code snippet?
const fs = require('fs');
const stream = fs.createReadStream('file.txt');
stream.emit('error', new Error('File not found'));medium
Solution
Step 1: Understand error event emission
Error events on streams are emitted by the system when errors occur, not manually by user code.Step 2: Identify the misuse of emit
Callingemit('error')manually on a stream is not standard practice and can cause unexpected behavior.Final Answer:
Manually emitting 'error' event is incorrect; errors should come from the system -> Option AQuick Check:
Don't manually emit 'error' on streams [OK]
Hint: Let system emit errors; don't call emit('error') yourself [OK]
Common Mistakes:
- Thinking manual emit is normal
- Assuming missing listener causes error here
- Believing file path must be absolute always
5. You want to create a simple HTTP server in Node.js that handles errors gracefully. Which code snippet correctly handles errors on the server to avoid crashes?
hard
Solution
Step 1: Identify proper error handling on server
Listening to the 'error' event on the server allows catching errors and logging them without crashing.Step 2: Check other options for issues
const http = require('http'); const server = http.createServer((req, res) => { throw new Error('Oops'); }); server.listen(3000); throws error inside request handler without catching, causing crash. const http = require('http'); const server = http.createServer((req, res) => { res.end('Hello'); }); server.emit('error', new Error('Oops')); server.listen(3000); manually emits error, which is wrong. const http = require('http'); const server = http.createServer((req, res) => { res.end('Hello'); }); server.on('request', (req, res) => { throw new Error('Oops'); }); server.listen(3000); throws error inside 'request' event without handling.Final Answer:
Code that listens to 'error' event and logs errors -> Option BQuick Check:
Listen to 'error' event on server to handle errors [OK]
Hint: Always listen to 'error' event on servers to avoid crashes [OK]
Common Mistakes:
- Throwing errors without try/catch or error event listener
- Manually emitting error events on server
- Ignoring error events causing app crash
