Complete the code to listen for an error event on a Node.js EventEmitter.
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('error', [1] => { console.error('Error occurred:', [1].message); });
The error event handler receives the error object as the first argument. Using err is a common convention.
Complete the code to emit an error event with a custom error message.
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.emit('error', new [1]('Something went wrong'));
In Node.js, errors are usually instances of the built-in Error class.
Fix the error in the code to properly handle errors emitted by the EventEmitter.
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('error', function([1]) { console.log('An error happened:', [1].message); });
The error handler function must accept the error object as a parameter to access its properties.
Fill both blanks to create an error handler that logs the error stack and exits the process.
emitter.on('error', ([1]) => { console.error([2].stack); process.exit(1); });
stack on a variable that is not the error object.The error object is passed as a parameter, commonly named err, and its stack property shows the error trace.
Fill all three blanks to create a try-catch block that emits an error event on failure.
try { JSON.parse([1]); } catch ([2]) { emitter.emit([3], [2]); }
The JSON.parse method parses a JSON string. The catch block catches the error as err and emits an 'error' event with it.