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?
>Solution :
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)
})