node.js - 无法在 try catch block 中捕获 TCP 客户端错误 | NodeJS

标签 node.js tcp error-handling thrift es6-class

我正在使用 Thrift 客户端向 NodeJS 中的远程服务器发出请求。然而我陷入了困境。

这就是我初始化客户端连接并执行 Tcommand 的方式

    try {
      const TClient = Thrift.getThriftClient()
      const status = await TClient.runCommand(expCommand)
    } catch (error) {
      throw error  // I need exception to be caught here.
    }

在 Thrift.getTriftClient() 方法中,我使用

 getTriftClient () {
    const thriftClient = thrift.createClient(command, this.getConnection())
    return thriftClient
  }


getConnection () {
    const connection = thrift.createConnection(this.host, this.port, {
      transport: this.transport,
      protocol: this.protocol
    })

    connection.on('error', (err) => {
      logger.error(scriptName, 'Thrift connection error', err)
      throw new Error('Not able to catch this in try catch')
    })

    return connection
  }

现在我的问题是我无法重新抛出在错误事件监听器 block 中遇到的任何异常。我想要的是捕获第一个错误 block 实例中的异常。

有什么办法我可以做到吗?

最佳答案

try {
  const TClient = Thrift.getThriftClient()
  const status = await TClient.runCommand(expCommand)
} catch (error) {
  throw error  // I need exception to be caught here.
}

try/catch block 方式的错误处理是针对同步代码的。

错误处理的 async/await 方式适用于异步代码。

您在 AsyncFunction 实例(异步函数)内有一个等待运算符,因此您有异步代码,因此您正在使用 Promises,Promises 将解析为一个值或拒绝,可能会出现一个 Error 实例。

而不是同步:

try {
  const TClient = Thrift.getThriftClient()
  const status = await TClient.runCommand(expCommand)
} catch (error) {
  throw error  // I need exception to be caught here.
}

执行异步:

const TClient = Thrift.getThriftClient()
.then((client) => {
  return TClient.runCommand(expCommand);
})
.then((commandResult) => {
  console.log(commandResult);
})
.catch((err) => {
  throw err;
});

关于node.js - 无法在 try catch block 中捕获 TCP 客户端错误 | NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50194025/

相关文章:

node.js - API触发消息的头像如何设置?

php - 如何在 Zend 中正确设置异常处理程序?

javascript - 在 Array.forEach block 中的所有 Promise 都已解决后返回

javascript - 在 Node.js 中让方法返回 Bluebird 的虚拟 promise 的正确方法是什么

java - 通过 TCP 发送文本

python - Django 中的持久 TCP 连接

networking - 设计和实现网络协议(protocol)的最佳实践是什么?

sql - 如何创建存储过程以将数据从查询复制到临时表?

javascript - 如果图像正常,为什么和img onerror处理程序一起执行

javascript - 如何在 Discord.js 中按名称查找表情符号