Add error handling for Yjs operations

This commit is contained in:
Jared Miller 2026-01-27 16:17:53 -05:00
parent 68a7517dec
commit 73ee70c52a
Signed by: shmup
GPG key ID: 22B5C6D66A38B06C
2 changed files with 25 additions and 9 deletions

View file

@ -42,10 +42,16 @@ function connect(roomName: string) {
case "sync": case "sync":
case "update": { case "update": {
if (!doc) break; if (!doc) break;
suppressLocal = true; try {
Y.applyUpdate(doc, new Uint8Array(msg.data)); suppressLocal = true;
suppressLocal = false; Y.applyUpdate(doc, new Uint8Array(msg.data));
send({ type: "content", text: text?.toString() || "" }); suppressLocal = false;
send({ type: "content", text: text?.toString() || "" });
} catch (err) {
suppressLocal = false;
console.error("failed to apply yjs update:", err);
send({ type: "error", message: "failed to apply remote update" });
}
break; break;
} }
case "peers": { case "peers": {

View file

@ -28,11 +28,21 @@ export class Session {
} }
applyUpdate(update: Uint8Array, from: Client) { applyUpdate(update: Uint8Array, from: Client) {
Y.applyUpdate(this.doc, update); try {
// broadcast to others Y.applyUpdate(this.doc, update);
for (const client of this.clients) { // broadcast to others
if (client !== from) { for (const client of this.clients) {
client.ws.send(encode({ type: "update", data: Array.from(update) })); if (client !== from) {
client.ws.send(encode({ type: "update", data: Array.from(update) }));
}
}
} catch (err) {
console.error(`failed to apply update in session ${this.name}:`, err);
// optionally notify the client that sent the bad update
try {
from.ws.send(encode({ type: "error", message: "invalid update" } as any));
} catch {
// ignore send errors
} }
} }
} }