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

时间:2018-08-12 12:38:43

标签: javascript node.js sockets

当我向套接字(IRC服务器,特别是Twitch)发送消息时,我试图创建try / catch

矿井一直在向套接字发送消息。在某一时刻,另一方(在本例中为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' }

2 个答案:

答案 0 :(得分:0)

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

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

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

更多示例,请访问https://runnable.com/blog/handling-errors-with-es6。 希望对您有所帮助。

答案 1 :(得分:0)

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

read.csv