Skip to content

Commit c2fd342

Browse files
committed
fix: exit with an error if server unexpectedly closes the connection
1 parent ab4c6d9 commit c2fd342

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

src/APIClient.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ export class APIClient {
1717
private socket: WebSocket;
1818
private connectionAttempts = 0;
1919
private lastId = 0;
20+
private closed = false;
2021
private _running = false;
2122
private _lastNanos = 0;
2223
private readonly pendingCommands = new Map<
@@ -70,6 +71,18 @@ export class APIClient {
7071
this.socket.addEventListener('error', (event) => {
7172
reject(new Error(`Error connecting to ${this.server}: ${event.message}`));
7273
});
74+
this.socket.addEventListener('close', (event) => {
75+
if (this.closed) {
76+
return;
77+
}
78+
79+
const message = `Connection to ${this.server} closed unexpectedly: code ${event.code}`;
80+
if (this.onError) {
81+
this.onError({ type: 'error', message });
82+
} else {
83+
console.error(message);
84+
}
85+
});
7386
});
7487
}
7588

@@ -213,6 +226,7 @@ export class APIClient {
213226
}
214227

215228
close() {
229+
this.closed = true;
216230
if (this.socket.readyState === WebSocket.OPEN) {
217231
this.socket.close();
218232
}

0 commit comments

Comments
 (0)