Add WebSocket.send() error handling
This commit is contained in:
parent
bad4cdac51
commit
2de33370cd
2 changed files with 28 additions and 6 deletions
10
src/index.ts
10
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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue