From 2de33370cdff29567c07a35a706c897883c83e8c Mon Sep 17 00:00:00 2001 From: Jared Miller Date: Tue, 27 Jan 2026 17:57:04 -0500 Subject: [PATCH] Add WebSocket.send() error handling --- src/index.ts | 10 +++++++--- src/session.ts | 24 +++++++++++++++++++++--- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index 39e433d..6991854 100644 --- a/src/index.ts +++ b/src/index.ts @@ -47,9 +47,13 @@ Bun.serve({ switch (msg.type) { case "join": { if (!isValidRoomName(msg.room)) { - ws.send( - JSON.stringify({ type: "error", message: "invalid room name" }), - ); + try { + ws.send( + JSON.stringify({ type: "error", message: "invalid room name" }), + ); + } catch (err) { + console.debug("failed to send error to client:", err); + } break; } const session = getOrCreateSession(msg.room); diff --git a/src/session.ts b/src/session.ts index f349d7a..26b555d 100644 --- a/src/session.ts +++ b/src/session.ts @@ -18,7 +18,13 @@ export class Session { this.clients.add(client); // send full state to new client const state = Y.encodeStateAsUpdate(this.doc); - client.ws.send(encode({ type: "sync", data: Array.from(state) })); + try { + client.ws.send(encode({ type: "sync", data: Array.from(state) })); + } catch (err) { + console.debug("failed to send sync to client, removing:", err); + this.clients.delete(client); + return; + } this.broadcastPeerCount(); } @@ -37,7 +43,14 @@ export class Session { // broadcast to others for (const client of this.clients) { if (client !== from) { - client.ws.send(encode({ type: "update", data: Array.from(update) })); + try { + client.ws.send( + encode({ type: "update", data: Array.from(update) }), + ); + } catch (err) { + console.debug("failed to send update to client, removing:", err); + this.clients.delete(client); + } } } } catch (err) { @@ -54,7 +67,12 @@ export class Session { broadcastPeerCount() { const msg = encode({ type: "peers", count: this.clients.size }); for (const client of this.clients) { - client.ws.send(msg); + try { + client.ws.send(msg); + } catch (err) { + console.debug("failed to send peer count to client, removing:", err); + this.clients.delete(client); + } } } }