Skip to content

Commit

Permalink
fix(TypedMessenger): Make sure errors while handling received message…
Browse files Browse the repository at this point in the history
…s are caught correctly
  • Loading branch information
jespertheend committed Oct 20, 2024
1 parent 4fb5c9b commit 359a8a1
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/util/TypedMessenger/TypedMessenger.js
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,7 @@ export class TypedMessenger {
try {
if (typeof message.data == "string") {
const parsed = JSON.parse(message.data);
this.handleReceivedMessage(parsed);
await this.handleReceivedMessage(parsed);
}
} catch (e) {
console.error("An error occurred while handling a websocket message.", message.data, e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { TypedMessenger } from "../../../../../../src/util/TypedMessenger/TypedM
import { assertSpyCalls, stub } from "std/testing/mock.ts";
import { assertPromiseResolved } from "../../../../../../src/util/asserts.js";
import { createLinkedMessengers, createLinkedWebSockets } from "./shared/websockets.js";
import { waitForMicrotasks } from "../../../../../../src/util/waitForMicroTasks.js";

Deno.test({
name: "initializeWebSocket()",
Expand Down Expand Up @@ -78,3 +79,28 @@ Deno.test({
}
},
});

Deno.test({
name: "Errors due to websocket closing before a response message is sent are caught",
async fn() {
const consoleSpy = stub(console, "error", () => {});

try {
const { socketA, socketB } = createLinkedWebSockets();
const { messengerB } = createLinkedMessengers(socketA, socketB, {
foo() {
return "foo";
},
}, {});
socketA.close();
const sendPromise = messengerB.send.foo();

await waitForMicrotasks();
assertSpyCalls(consoleSpy, 1);
assertEquals(consoleSpy.calls[0].args[0], "An error occurred while handling a websocket message.");
await assertPromiseResolved(sendPromise, false);
} finally {
consoleSpy.restore();
}
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ class FakeWebSocket extends EventTarget {
* @param {string} data
*/
send(data) {
if (this.#readyState != WebSocket.OPEN) {
throw new DOMException("readyState not OPEN", "InvalidStateError");
}
this.#otherSocket?.dispatchEvent(new MessageEvent("message", {
data,
}));
Expand All @@ -24,6 +27,11 @@ class FakeWebSocket extends EventTarget {
this.dispatchEvent(new Event("open"));
}

close() {
this.#readyState = WebSocket.CLOSED;
this.dispatchEvent(new Event("close"));
}

error() {
this.dispatchEvent(new Event("error"));
}
Expand Down

0 comments on commit 359a8a1

Please sign in to comment.