Skip to content

Commit

Permalink
fix(websocket): ignore resource close error (denoland#9755)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
lucacasonato committed Apr 1, 2021
1 parent 2d7fdb0 commit 0e72129
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions op_crates/websocket/01_websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,19 @@
}
}

/**
* 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) {
Expand Down Expand Up @@ -125,7 +138,7 @@
const event = new CloseEvent("close");
event.target = this;
this.dispatchEvent(event);
core.close(this.#rid);
tryClose(this.#rid);
});
} else {
this.#readyState = OPEN;
Expand Down Expand Up @@ -289,7 +302,7 @@
});
event.target = this;
this.dispatchEvent(event);
core.close(this.#rid);
tryClose(this.#rid);
});
}
}
Expand Down Expand Up @@ -350,7 +363,7 @@
});
event.target = this;
this.dispatchEvent(event);
core.close(this.#rid);
tryClose(this.#rid);

break;
}
Expand All @@ -365,7 +378,7 @@
const closeEv = new CloseEvent("close");
closeEv.target = this;
this.dispatchEvent(closeEv);
core.close(this.#rid);
tryClose(this.#rid);

break;
}
Expand Down

0 comments on commit 0e72129

Please sign in to comment.