The correct answer is B .
This question is about the event-driven programming model commonly used in Node.js. Many Node.js libraries expose an .on() method to register callback functions for specific events.
The correct pattern is:
ws.on( ' eventName ' , callbackFunction);
In this case, the developer needs to listen for two events:
' connect '
and:
' error '
The correct implementation is:
ws.on( ' connect ' , () = > {
console.log( ' Connected to client ' );
});
ws.on( ' error ' , (error) = > {
console.log( ' ERROR ' , error);
});
This registers one listener for successful connection and another listener for connection errors.
Why this works professionally:
ws.on( ' connect ' , callback) tells the library:
“When the connection event happens, execute this callback.”
ws.on( ' error ' , callback) tells the library:
“When an error event happens, execute this callback and pass the error object into it.”
Option A is incorrect because .catch() is used with Promises. The question specifically says the client library is built using events and callbacks , not Promise chaining.
Option D is incorrect because try...catch only catches synchronous errors during the immediate execution of ws.connect(). It will not reliably catch asynchronous connection errors emitted later by the web socket client.
Option C is identical to option B in the provided question. Since the expected answer normally requires selecting one option, B is selected as the verified answer.
Therefore, the verified answer is B .