【问题标题】:How can I gracefully handle a failed tcpSocket.connect attempt?如何优雅地处理失败的 tcpSocket.connect 尝试?
【发布时间】:2019-06-18 06:02:29
【问题描述】:

当指定主机上没有可与之通信的现有 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 [as oncomplete] (net.js:1186:14)

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

  • 为什么我的 catch 块没有捕捉到错误?
  • 如何优雅地处理错误?

【问题讨论】:

    标签: node.js


    【解决方案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().
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多