繁体   English   中英

使用Node JS写入套接字时尝试捕获错误

[英]Trying to catch error when writing to socket using Node JS

当我向套接字发送消息时尝试创建try / catch(IRC服务器,专门用于Twitch)

我的不断向插座发送消息。 在某一时刻,另一方(在本例中为Twitch)将终止连接。 我需要捕获该错误,然后重新连接

我有这个代码。 尝试和捕获不起作用

Bot.irc = new tls.TLSSocket()

Bot.irc.connect({
    host: 'irc.chat.twitch.tv',
    port: this.port
  })

Bot.writeIrcMessage = (msg) => {
    console.log('writing irc msg > ', msg)

    try {
        Bot.irc.write(msg + "\r\n")
    }
    catch (e) {
        console.log('error writing irc message: ', e)
    }
}

这是我的控制台中的错误

writing irc msg >  JOIN #twitchusername
{ Error: This socket has been ended by the other party
    at TLSSocket.writeAfterFIN [as write] (net.js:356:12)
    at TwitchBot.Bot.writeIrcMessage (/home/node/chatbot/libs/bot.js:22:17)
    at TwitchBot.join (/home/node/chatbot/node_modules/twitch-bot/lib/bot.js:145:10)
    at /home/node/chatbot/libs/bot.js:101:17
    at new Promise (<anonymous>)
    at Object.join (/home/node/chatbot/libs/bot.js:92:37)
    at _callee2$ (/home/node/chatbot/libs/messagequeue.js:87:17)
    at tryCatch (/home/node/chatbot/node_modules/babel-polyfill/node_modules/regenerator-runtime/runtime.js:65:40)
    at Generator.invoke [as _invoke] (/home/node/chatbot/node_modules/babel-polyfill/node_modules/regenerator-runtime/runtime.js:303:22)
    at Generator.prototype.(anonymous function) [as next] (/home/node/chatbot/node_modules/babel-polyfill/node_modules/regenerator-runtime/runtime.js:117:21) code: 'EPIPE' }

我认为由于nodejs套接字固有的异步特性,未捕获到错误。

因此,如果api不提供回调(如.write(msg,函数ack(错误){})),则可以使用ES6 Promises。 通用示例:

const myFunc = function () {
  return doSomething()
    .then(a => {
      return Promise.all([a, doSomethingelse()])
    })
}

有关更多示例, 请参见https://runnable.com/blog/handling-errors-with-es6 希望能帮助到你。

侦听errorend消息:

Bot.irc.on('error', msg => { 
    // Handle the error, e.g., by reconnecting.
});
Bot.irc.on('end', msg => {
    // Can't write to a socket that ended. 
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM