如何妥善处理失败的tcpSocket.connect尝试?

时间:2019-01-24 13:24:31

标签: node.js

当指定主机上没有与之通信的TCP服务器时,以下代码将导致错误:

const net = require('net');
const argv = require('minimist')(process.argv.slice(2));

try {
    var tcpSocket = new net.Socket();
    tcpSocket.connect(argv.tcpport, argv.tcphost, function onConnected() {
        console.log('connected');
        tcpSocket.on('data', function onIncoming(data) {
            console.log(data);
        });

        tcpSocket.on('close', function onClose(data) {
            tcpSocketConnected = false;
        });

        tcpSocketConnected = true;
    });
} catch (err) {
    console.log("PRINT ME: ", err);
}

错误:

  

events.js:183         投掷者//未处理的“错误”事件         ^

     

错误:连接ECONNREFUSED 127.0.0.1:1906       在Object._errnoException(util.js:992:11)       在_exceptionWithHostPort(util.js:1014:20)       在TCPConnectWrap.afterConnect上[作为oncomplete](net.js:1186:14)

即使将代码包装在try...catch中,我也无法捕获错误。

  • 为什么我的catch块无法捕获错误?
  • 如何优雅地处理错误?

1 个答案:

答案 0 :(得分:1)

您应该能够使用事件发射器api显式处理error事件(与处理closedata的方式相同):

tcpSocket.on('error', handleError)

来自文档:

Event: 'error'#
Added in: v0.1.90
<Error>
Emitted when an error occurs. Unlike net.Socket, the 'close' event 
will not be emitted directly following this event unless server.close() 
is manually called. See the example in discussion of server.listen().