I am creating a socket that will take user input for the connection. Ideally because with user input there is inherently error involved i want to beable to handle the cases where the socket can not connect to the desired Address:Port
combo.
Using the node.js "Net" API I can easilly create a client socket connection to the server. We will create a function that allows for user input to the socket
function createConnection(HOST,PORT){
let socket = new net.Socket();
socket.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
socket.write(SomeData)
}
socket.on("data", (data) => {
console.log("data")
})
socket.on("error", (err) => {
console.log(err," This Error Occured!")
})
socket.on("close", () => {
console.log("Closing Connection")
})
}
Then we can call that function to create a socket connection with user defined parameters. My issue is that whether I wrap the function in a try catch as follows
try{
createConnection(userInputedHost, userInputedPort)
} catch (error) {
console.log(error, "This Error Occured!")
}
to handle a connection error or if i use the error
event defined in the socket creation i am never able to see the string "This Error Occured!"
and instead have my console flooded with the default exception
node:events:505
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:3977
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16)
Emitted 'error' event on Socket instance at:
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3977
}
Am I not using try catch blocks correctly, am I not understanding the error event form the net
API? Is there a way to handle an improper connection request without casing the node app to crash?