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;
try {
suppressLocal = true; suppressLocal = true;
Y.applyUpdate(doc, new Uint8Array(msg.data)); Y.applyUpdate(doc, new Uint8Array(msg.data));
suppressLocal = false; suppressLocal = false;
send({ type: "content", text: text?.toString() || "" }); 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,6 +28,7 @@ export class Session {
} }
applyUpdate(update: Uint8Array, from: Client) { applyUpdate(update: Uint8Array, from: Client) {
try {
Y.applyUpdate(this.doc, update); Y.applyUpdate(this.doc, update);
// broadcast to others // broadcast to others
for (const client of this.clients) { for (const client of this.clients) {
@ -35,6 +36,15 @@ export class Session {
client.ws.send(encode({ type: "update", data: Array.from(update) })); 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
}
}
} }
broadcastPeerCount() { broadcastPeerCount() {