net: net.Server.listen() avoid operations on null when fail

When `net.Server` fails to create a new handle, an error shall be
emitted in the next tick. Therefore, we make `net.Server.listen()`
directly  return to avoid following operations on `null`
`this._handle`.

Fixes: https://github.com/nodejs/node/issues/23917

PR-URL: https://github.com/nodejs/node/pull/23920
Reviewed-By: Richard Lau <riclau@uk.ibm.com>
Reviewed-By: Daniel Bevenius <daniel.bevenius@gmail.com>
This commit is contained in:
Ouyang Yadong 2018-10-27 15:44:50 +08:00 committed by Rich Trott
parent 04a291abec
commit 3458e65127
2 changed files with 27 additions and 0 deletions

View File

@ -1435,6 +1435,13 @@ Server.prototype.listen = function(...args) {
backlog = options.backlog || backlogFromArgs;
listenInCluster(this, pipeName, -1, -1,
backlog, undefined, options.exclusive);
if (!this._handle) {
// Failed and an error shall be emitted in the next tick.
// Therefore, we directly return.
return this;
}
let mode = 0;
if (options.readableAll === true)
mode |= PipeConstants.UV_READABLE;

View File

@ -69,3 +69,23 @@ function randomPipePath() {
srv.close();
}));
}
// Test should emit "error" events when listening fails.
{
const handlePath = randomPipePath();
const srv1 = net.createServer().listen({ path: handlePath }, () => {
// As the handlePath is in use, binding to the same address again should
// make the server emit an 'EADDRINUSE' error.
const srv2 = net.createServer()
.listen({
path: handlePath,
writableAll: true,
}, common.mustNotCall());
srv2.on('error', common.mustCall((err) => {
srv1.close();
assert.strictEqual(err.code, 'EADDRINUSE');
assert(/^listen EADDRINUSE: address already in use/.test(err.message));
}));
});
}