Skip to content

Commit dc0ecbc

Browse files
committed
Add try-catch around send
1 parent 3183538 commit dc0ecbc

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed

src/polyfill/RTCDataChannel.ts

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -176,23 +176,35 @@ export default class RTCDataChannel extends EventTarget implements globalThis.RT
176176
}
177177

178178
// Needs network error, type error implemented
179-
if (typeof data === 'string') {
180-
this.#dataChannel.sendMessage(data);
181-
} else if (data instanceof Blob) {
182-
data.arrayBuffer().then((ab) => {
179+
try {
180+
if (typeof data === 'string') {
181+
this.#dataChannel.sendMessage(data);
182+
} else if (data instanceof Blob) {
183+
data.arrayBuffer().then((ab) => {
184+
if (process?.versions?.bun) {
185+
this.#dataChannel.sendMessageBinary(Buffer.from(ab));
186+
} else {
187+
this.#dataChannel.sendMessageBinary(new Uint8Array(ab));
188+
}
189+
});
190+
} else if (data instanceof Uint8Array) {
191+
this.#dataChannel.sendMessageBinary(data);
192+
} else {
183193
if (process?.versions?.bun) {
184-
this.#dataChannel.sendMessageBinary(Buffer.from(ab));
194+
this.#dataChannel.sendMessageBinary(Buffer.from(data));
185195
} else {
186-
this.#dataChannel.sendMessageBinary(new Uint8Array(ab));
196+
this.#dataChannel.sendMessageBinary(new Uint8Array(data));
187197
}
188-
});
189-
} else if (data instanceof Uint8Array) {
190-
this.#dataChannel.sendMessageBinary(data);
191-
} else {
192-
if (process?.versions?.bun) {
193-
this.#dataChannel.sendMessageBinary(Buffer.from(data));
198+
}
199+
} catch (error) {
200+
//If error contains "DataChannel is closed" throw InvalidStateError
201+
if (error instanceof Error && error.message.includes('DataChannel is closed')) {
202+
throw new exceptions.InvalidStateError(
203+
"Failed to execute 'send' on 'RTCDataChannel': RTCDataChannel.readyState is not 'open'",
204+
);
194205
} else {
195-
this.#dataChannel.sendMessageBinary(new Uint8Array(data));
206+
// Otherwise throw the error
207+
throw error;
196208
}
197209
}
198210
}

0 commit comments

Comments
 (0)