JS-Dev-101 practice question 20 of 25

A Node.js server library uses events and callbacks. The developer wants to log any issues the server has at boot time. Which code logs an error with an event?

Full set: 148 questions
Answer options
A: server.catch('error) => { console.log('ERROR', error); });
B: server.error('error) => { console.log('ERROR', error); });
C: server.on('error', (error) => { console.log('ERROR', error); }); Correct answer
D: try { server.start(); } catch(error) { console.log('ERROR', error); }
Correct Answer:
C. server.on('error', (error) => { console.log('ERROR', error); });
Explanation

In Node.js, objects that emit events are instances of the EventEmitter class. The standard way to subscribe to an event is by using the .on() method. The first argument is the name of the event, and the second is a callback function to execute when the event is emitted. For handling errors in an event-driven architecture, the conventional event name is 'error'. This code correctly attaches a listener to the error event on the server object.

Why Incorrect

A. server.catch(...) is the syntax for handling promise rejections, not for listening to events from an EventEmitter.
B. server.error(...) is not a standard method on the EventEmitter class for listening to error events.
D. try...catch blocks are used for handling synchronous exceptions, not for handling asynchronously emitted 'error' events.

References

1. Node.js v18.17.1 Documentation, "Events" module, Class: EventEmitter, emitter.on(eventName, listener). Section: "The EventEmitter class".

2. Node.js v18.17.1 Documentation, "Error handling", Section: "Errors in synchronous vs. asynchronous code". It distinguishes between synchronous try...catch and asynchronous patterns like the 'error' event.

Scroll to Top