skip to Main Content

I am trying to connect to a socket that DOES NOT exist for testing purposes. In such case, an exception is thrown and I expect it to be caught in the following try/catch block. createConnection is imported from the net package.

try {
    createConnection(8000, "127.0.0.1")
}
catch(exception) {
    console.log("FAILED")
}

However, the try/catch fails and it leads to a crash by producing the following error:

node:events:368
    throw er; // Unhandled 'error' event
    ^

Error: connect ECONNREFUSED 127.0.0.1:8000
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161: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: 8000
}

What’s going wrong here? and if that is supposed to be like that, then how can I safeguard the application from crashing when a socket is not available?

2

Answers


  1. The try-catch block does only catch errors the are emitted through a throw in createConnection.

    The error in question however is an error that is reported through an error event that you need to listen to.

    createConnection returns a Socket that implements EventEmitter on which you can register listeners for e.g. error events.

    So it has to be:

    createConnection(…)
    .on('error', err => {
      console.error(err)
    })
    
    Login or Signup to reply.
  2. I’m pretty sure that this function is asynchronous and you have to listen for error event

    const connection = createConnection(8000, "127.0.0.1")
    connection.on('error', error => {
      // handle error
    })
    

    If you really want to use try...catch:

    function createConn(port, ip) {
      return new Promise((resolve, reject) => {
        const connection = createConnection(port, ip)
        connection.on('ready', resolve)
        connection.on('error', reject)
      })
    }
    
    try {
      await createConn(8000, "127.0.0.1")
    } catch (error) {
      // handle error
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search