0
0
Node.jsframework~10 mins

Error events and handling in Node.js - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to listen for an error event on a Node.js EventEmitter.

Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('error', [1] => {
  console.error('Error occurred:', [1].message);
});
Drag options to blanks, or click blank then click option'
Aevent
Berror
Cerr
De
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'event' or 'error' as the parameter name without matching usage inside the function.
Not providing a parameter to the callback function.
2fill in blank
medium

Complete the code to emit an error event with a custom error message.

Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.emit('error', new [1]('Something went wrong'));
Drag options to blanks, or click blank then click option'
AException
BMessage
CEvent
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent class like 'Exception' or 'Message'.
Passing a string directly instead of an Error object.
3fill in blank
hard

Fix the error in the code to properly handle errors emitted by the EventEmitter.

Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('error', function([1]) {
  console.log('An error happened:', [1].message);
});
Drag options to blanks, or click blank then click option'
Aerr
Berror
Cthis
Devent
Attempts:
3 left
💡 Hint
Common Mistakes
Not defining a parameter in the callback function.
Using 'this' to access the error object.
4fill in blank
hard

Fill both blanks to create an error handler that logs the error stack and exits the process.

Node.js
emitter.on('error', ([1]) => {
  console.error([2].stack);
  process.exit(1);
});
Drag options to blanks, or click blank then click option'
Aerr
Berror
Ce
Devent
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the parameter and inside the function.
Trying to access stack on a variable that is not the error object.
5fill in blank
hard

Fill all three blanks to create a try-catch block that emits an error event on failure.

Node.js
try {
  JSON.parse([1]);
} catch ([2]) {
  emitter.emit([3], [2]);
}
Drag options to blanks, or click blank then click option'
A'{"name":"John"}'
Berr
C'error'
D'data'
Attempts:
3 left
💡 Hint
Common Mistakes
Using invalid JSON string in the first blank.
Using wrong parameter name in catch block.
Emitting a wrong event name instead of 'error'.