diff --git a/cli/tests/unit_node/http_test.ts b/cli/tests/unit_node/http_test.ts index 706c672f14..9feee02728 100644 --- a/cli/tests/unit_node/http_test.ts +++ b/cli/tests/unit_node/http_test.ts @@ -751,3 +751,29 @@ Deno.test( assertEquals(body, "hello"); }, ); + +Deno.test("[node/http] server emits error if addr in use", async () => { + const promise = deferred(); + const promise2 = deferred(); + + const server = http.createServer(); + server.listen(9001); + + const server2 = http.createServer(); + server2.on("error", (e) => { + promise2.resolve(e); + }); + server2.listen(9001); + + const err = await promise2; + server.close(() => promise.resolve()); + server2.close(); + await promise; + const expectedMsg = Deno.build.os === "windows" + ? "Only one usage of each socket address" + : "Address already in use"; + assert( + err.message.startsWith(expectedMsg), + `Wrong error: ${err.message}`, + ); +}); diff --git a/ext/node/polyfills/http.ts b/ext/node/polyfills/http.ts index 609a046ac8..52aac4caec 100644 --- a/ext/node/polyfills/http.ts +++ b/ext/node/polyfills/http.ts @@ -1610,19 +1610,25 @@ export class ServerImpl extends EventEmitter { return; } this.#ac = ac; - this.#server = serve( - { - handler: handler as Deno.ServeHandler, - ...this.#addr, - signal: ac.signal, - // @ts-ignore Might be any without `--unstable` flag - onListen: ({ port }) => { - this.#addr!.port = port; - this.emit("listening"); + try { + this.#server = serve( + { + handler: handler as Deno.ServeHandler, + ...this.#addr, + signal: ac.signal, + // @ts-ignore Might be any without `--unstable` flag + onListen: ({ port }) => { + this.#addr!.port = port; + this.emit("listening"); + }, + ...this._additionalServeOptions?.(), }, - ...this._additionalServeOptions?.(), - }, - ); + ); + } catch (e) { + this.emit("error", e); + return; + } + if (this.#unref) { this.#server.unref(); }