Bird
Raised Fist0
Node.jsframework~20 mins

Error events and handling in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Node.js Error Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when an 'error' event is emitted without a listener?
Consider this Node.js code snippet that emits an 'error' event on an EventEmitter without any listener attached. What will happen when this code runs?
Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.emit('error', new Error('Something went wrong'));
AThe error event is queued until a listener is added.
BThe error event is ignored silently.
CThe error is logged to the console but the program continues.
DThe program throws an uncaught error and crashes.
Attempts:
2 left
💡 Hint
Think about Node.js default behavior when an 'error' event has no listeners.
state_output
intermediate
2:00remaining
What is the output after handling an error event?
Given this code, what will be printed to the console?
Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('error', (err) => {
  console.log('Caught error:', err.message);
});
emitter.emit('error', new Error('Oops!'));
AUncaught Error: Oops!
BCaught error: Oops!
CNothing is printed.
DCaught error: undefined
Attempts:
2 left
💡 Hint
Check how the error message is accessed inside the listener.
📝 Syntax
advanced
2:00remaining
Which option correctly attaches an error event listener?
Select the code snippet that correctly attaches an 'error' event listener to an EventEmitter instance named 'emitter'.
Aemitter.addListener('error', err => console.log(err.message));
Bemitter.on('error', function(err) { console.log(err); });
Cemitter.error(function(err) { console.log(err); });
Demitter.listen('error', (err) => console.log(err));
Attempts:
2 left
💡 Hint
Check the correct method names for attaching event listeners in Node.js EventEmitter.
🔧 Debug
advanced
2:00remaining
Why does this error handler not catch the error?
Look at this code snippet. Why does the error handler not catch the emitted error?
Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.emit('error', new Error('Fail'));
emitter.on('error', (err) => {
  console.log('Error caught:', err.message);
});
AThe error event was emitted before the listener was attached.
BThe listener function has a syntax error.
CThe error object is not passed correctly to the listener.
DThe EventEmitter instance does not support error events.
Attempts:
2 left
💡 Hint
Consider the order of event emission and listener attachment.
🧠 Conceptual
expert
3:00remaining
What is the best practice to avoid crashing on error events in Node.js?
Which approach best prevents the Node.js process from crashing due to unhandled 'error' events on EventEmitters?
AUse process.on('uncaughtException') to handle all errors globally.
BWrap every emit call in try-catch blocks.
CAlways attach an 'error' event listener to every EventEmitter instance.
DIgnore error events and let the process crash to fix bugs quickly.
Attempts:
2 left
💡 Hint
Think about how Node.js expects error events to be handled on EventEmitters.

Practice

(1/5)
1. What is the main purpose of handling error events in Node.js event emitters?
easy
A. To improve the speed of the application
B. To automatically restart the server
C. To catch and respond to problems in asynchronous code
D. To log user activity

Solution

  1. Step 1: Understand the role of error events

    Error events in Node.js are emitted when something goes wrong in asynchronous operations.
  2. Step 2: Identify the purpose of handling errors

    Handling these events allows the program to respond properly, avoiding crashes and improving stability.
  3. Final Answer:

    To catch and respond to problems in asynchronous code -> Option C
  4. Quick 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
A. myStream.catch('error', (err) => { console.error(err); });
B. myStream.error((err) => { console.error(err); });
C. myStream.listen('error', (err) => { console.error(err); });
D. myStream.on('error', (err) => { console.error(err); });

Solution

  1. Step 1: Recall the event listener syntax in Node.js

    Node.js uses the on method to listen to events on event emitters like streams.
  2. Step 2: Verify the correct method and parameters

    The correct syntax is myStream.on('error', callback) where callback receives the error object.
  3. Final Answer:

    myStream.on('error', (err) => { console.error(err); }); -> Option D
  4. Quick 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
A. Error caught: Oops!
B. Unhandled 'error' event
C. Error: Oops!
D. No output

Solution

  1. 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:'.
  2. 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.
  3. Final Answer:

    Error caught: Oops! -> Option A
  4. Quick 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
A. Manually emitting 'error' event is incorrect; errors should come from the system
B. The error event listener is missing, so it will crash
C. The file path should be absolute
D. createReadStream does not emit error events

Solution

  1. Step 1: Understand error event emission

    Error events on streams are emitted by the system when errors occur, not manually by user code.
  2. Step 2: Identify the misuse of emit

    Calling emit('error') manually on a stream is not standard practice and can cause unexpected behavior.
  3. Final Answer:

    Manually emitting 'error' event is incorrect; errors should come from the system -> Option A
  4. Quick 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
A. const http = require('http'); const server = http.createServer((req, res) => { res.end('Hello'); }); server.emit('error', new Error('Oops')); server.listen(3000);
B. const http = require('http'); const server = http.createServer((req, res) => { res.end('Hello'); }); server.on('error', (err) => { console.error('Server error:', err); }); server.listen(3000);
C. const http = require('http'); const server = http.createServer((req, res) => { throw new Error('Oops'); }); server.listen(3000);
D. 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);

Solution

  1. Step 1: Identify proper error handling on server

    Listening to the 'error' event on the server allows catching errors and logging them without crashing.
  2. 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.
  3. Final Answer:

    Code that listens to 'error' event and logs errors -> Option B
  4. Quick 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