如何在 nodejs 中向调用方通知连接错误?



我正在使用nodejs进行websocket连接(https://github.com/websockets/ws(。我定义了一个connect方法,将Promise返回给调用方。这是代码:

connect = () => {
return new Promise((resolve, reject) => {
try {
this.ws = new WebSocket(this.url, {});
this.ws.on("open", () => {
console.log("connected:", this.ws.readyState);
resolve();
});
this.ws.on("close", function close() {
console.log("disconnected");
// how to throw error exception here?
});
} catch (err) {
reject(err);
}
});
};

调用方将调用此方法,并在连接失败时尝试重新连接。

connect().then(() => {
...
}).catch(() => {
// do reconnect
})

如果第一次连接失败,它工作正常。但是,如果连接断开怎么办。如何让呼叫者知道发生了错误?

我能想到的一个解决方案是创建一个event emitter来通知呼叫者我们需要重新连接。但是,如果代码在我的项目中的许多地方使用,我必须将event emitter传递到许多地方。有没有更好的方法可以做到这一点?

我不清楚你使用的是哪个 npm 包,但如果是 ws,你可以参考其自述文件的这一部分,并在必要时适应你的用例: https://github.com/websockets/ws/blob/master/README.md#how-to-detect-and-close-broken-connections

最新更新