Skip to content

Commit

Permalink
Merge pull request #39 from gelatodigital/chore/websocket-error-handling
Browse files Browse the repository at this point in the history
chore: websocket error handling
  • Loading branch information
denis-pingin committed Oct 17, 2023
2 parents b81cacb + 650ed78 commit 01fdf8b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@gelatonetwork/relay-sdk",
"version": "5.5.0",
"version": "5.5.2",
"description": "SDK to integrate with Gelato Relay",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
28 changes: 19 additions & 9 deletions src/utils/websocketHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ export class WebsocketHandler {
}, this.#reconnectIntervalMillis);
};

this.#websocket.onerror = (error: WebSocket.ErrorEvent) => {
this._handleError(error);
};

this.#websocket.onmessage = async (data: WebSocket.MessageEvent) => {
const message = JSON.parse(
data.data.toString()
Expand All @@ -133,9 +137,8 @@ export class WebsocketHandler {
const errorWebsocketMessage = message as ErrorWebsocketMessage;
const error: Error = errorWebsocketMessage.payload;

this.#errorHandlers.forEach((handler) => {
handler(error);
});
this._handleError(error);

break;
}
case WebsocketEvent.UPDATE: {
Expand Down Expand Up @@ -191,7 +194,10 @@ export class WebsocketHandler {
private async _ensureIsConnected(): Promise<boolean> {
if (!this.#websocket) {
this._connect();
} else if (this.#websocket.readyState !== WebSocket.OPEN) {
} else if (
this.#websocket.readyState !== WebSocket.CONNECTING &&
this.#websocket.readyState !== WebSocket.OPEN
) {
this._reconnect();
}
return await this._awaitConnection();
Expand All @@ -202,17 +208,21 @@ export class WebsocketHandler {
while (!this.#websocket || this.#websocket.readyState !== WebSocket.OPEN) {
const elapsed = Date.now() - start;
if (elapsed > this.#connectTimeoutMillis) {
const error = new Error(
`Timeout connecting to ${this.#url} after ${elapsed}ms`
this._handleError(
new Error(`Timeout connecting to ${this.#url} after ${elapsed}ms`)
);
this.#errorHandlers.forEach((handler) => {
handler(error);
});

return false;
}

await new Promise((resolve) => setTimeout(resolve, 10));
}
return true;
}

private _handleError(error: Error) {
this.#errorHandlers.forEach((handler) => {
handler(error);
});
}
}

0 comments on commit 01fdf8b

Please sign in to comment.