1

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?

1 Answer 1

0

The Awnser is to use

socket.on("error", (err) => {
        console.log(err," This Error Occured!")
    })

as described in this post. I had been implementing the proper use of the event but my issue was i was not compiling properly. I was going form .ts -> .js and had my tsconfig set wrong so none of the changes i made were being pushed to the js file. A closer inspection of the compiled js file showed that the error event code was never added in. Once solved everything works as intended

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.