我正在使用 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/