From 6356ad42ab73f7fbe074082c617900ae28763590 Mon Sep 17 00:00:00 2001 From: rickyes Date: Wed, 15 Apr 2020 13:23:26 +0800 Subject: [PATCH] lib: fix validateport error message when allowZero is false PR-URL: https://github.com/nodejs/node/pull/32861 Fixes: https://github.com/nodejs/node/issues/32857 Reviewed-By: Zeyu Yang Reviewed-By: Ben Noordhuis Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater --- lib/internal/errors.js | 8 ++++++-- lib/internal/validators.js | 2 +- test/parallel/test-dgram-connect.js | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 74efc248a6e130..bfb2dd556073b6 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -1310,8 +1310,12 @@ E('ERR_SERVER_NOT_RUNNING', 'Server is not running.', Error); E('ERR_SOCKET_ALREADY_BOUND', 'Socket is already bound', Error); E('ERR_SOCKET_BAD_BUFFER_SIZE', 'Buffer size must be a positive integer', TypeError); -E('ERR_SOCKET_BAD_PORT', - '%s should be >= 0 and < 65536. Received %s.', RangeError); +E('ERR_SOCKET_BAD_PORT', (name, port, allowZero = true) => { + assert(typeof allowZero === 'boolean', + "The 'allowZero' argument must be of type boolean."); + const operator = allowZero ? '>=' : '>'; + return `${name} should be ${operator} 0 and < 65536. Received ${port}.`; +}, RangeError); E('ERR_SOCKET_BAD_TYPE', 'Bad socket type specified. Valid types are: udp4, udp6', TypeError); E('ERR_SOCKET_BUFFER_SIZE', diff --git a/lib/internal/validators.js b/lib/internal/validators.js index 2d6c8a6ada2d51..1d7bf1baa19fa1 100644 --- a/lib/internal/validators.js +++ b/lib/internal/validators.js @@ -179,7 +179,7 @@ function validatePort(port, name = 'Port', { allowZero = true } = {}) { +port !== (+port >>> 0) || port > 0xFFFF || (port === 0 && !allowZero)) { - throw new ERR_SOCKET_BAD_PORT(name, port); + throw new ERR_SOCKET_BAD_PORT(name, port, allowZero); } return port | 0; } diff --git a/test/parallel/test-dgram-connect.js b/test/parallel/test-dgram-connect.js index a9815f439a731a..30e817f344a42c 100644 --- a/test/parallel/test-dgram-connect.js +++ b/test/parallel/test-dgram-connect.js @@ -60,7 +60,7 @@ assert.throws(() => { client.connect(port); }, { name: 'RangeError', - message: /^Port should be >= 0 and < 65536/, + message: /^Port should be > 0 and < 65536/, code: 'ERR_SOCKET_BAD_PORT' }); });