fix(websocket): ignore resource close error
It is possible that the WebSocket is already closed when we try to
close it with `WebSocket#close` or in the `error` or `close` events.
Currently this leads to an uncatchable promise rejection. This changes
this so that closing an already closed WebSocket is a noop.
}
}
+ /**
+ * Tries to close the resource (and ignores BadResource errors).
+ * @param {number} rid
+ */
+ function tryClose(rid) {
+ try {
+ core.close(rid);
+ } catch (err) {
+ // Ignore error if the socket has already been closed.
+ if (!(err instanceof Deno.errors.BadResource)) throw err;
+ }
+ }
+
const handlerSymbol = Symbol("eventHandlers");
function makeWrappedHandler(handler) {
function wrappedHandler(...args) {
const event = new CloseEvent("close");
event.target = this;
this.dispatchEvent(event);
- core.close(this.#rid);
+ tryClose(this.#rid);
});
} else {
this.#readyState = OPEN;
});
event.target = this;
this.dispatchEvent(event);
- core.close(this.#rid);
+ tryClose(this.#rid);
});
}
}
});
event.target = this;
this.dispatchEvent(event);
- core.close(this.#rid);
+ tryClose(this.#rid);
break;
}
const closeEv = new CloseEvent("close");
closeEv.target = this;
this.dispatchEvent(closeEv);
- core.close(this.#rid);
+ tryClose(this.#rid);
break;
}
