Skip to content

Commit 0cc1ea6

Browse files
matzavinosjasnell
authored andcommitted
lib/net: Convert to using internal/errors
Covert lib/net.js over to using lib/internal/errors.js Ref: nodejs#11273 I have not addressed the cases that use errnoException(), for reasons described in nodejsGH-12926 - Replace thrown errors in lib/net.js with errors from lib/internal/errors. The ERR_INVALID_OPT_VALUE error have been used in the Server.prototype.listen() method after a discussion in Ref: nodejs#14782 - Update tests according to the above modifications
1 parent 7e382c1 commit 0cc1ea6

9 files changed

+130
-97
lines changed

lib/net.js

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -61,10 +61,10 @@ const normalizedArgsSymbol = internalNet.normalizedArgsSymbol;
6161
function noop() {}
6262

6363
function createHandle(fd) {
64-
var type = TTYWrap.guessHandleType(fd);
64+
const type = TTYWrap.guessHandleType(fd);
6565
if (type === 'PIPE') return new Pipe();
6666
if (type === 'TCP') return new TCP();
67-
throw new TypeError('Unsupported fd type: ' + type);
67+
throw new errors.Error('ERR_INVALID_HANDLE_TYPE');
6868
}
6969

7070

@@ -695,8 +695,10 @@ protoGetter('localPort', function localPort() {
695695

696696
Socket.prototype.write = function(chunk, encoding, cb) {
697697
if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) {
698-
throw new TypeError(
699-
'Invalid data, chunk must be a string or buffer, not ' + typeof chunk);
698+
throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
699+
'chunk',
700+
['string', 'Buffer'],
701+
chunk);
700702
}
701703
return stream.Duplex.prototype.write.apply(this, arguments);
702704
};
@@ -1035,21 +1037,25 @@ function lookupAndConnect(self, options) {
10351037
var localPort = options.localPort;
10361038

10371039
if (localAddress && !cares.isIP(localAddress)) {
1038-
throw new TypeError('"localAddress" option must be a valid IP: ' +
1039-
localAddress);
1040+
throw new errors.Error('ERR_INVALID_IP_ADDRESS', localAddress);
10401041
}
10411042

10421043
if (localPort && typeof localPort !== 'number') {
1043-
throw new TypeError('"localPort" option should be a number: ' + localPort);
1044+
throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
1045+
'options.localPort',
1046+
['number'],
1047+
localPort);
10441048
}
10451049

10461050
if (typeof port !== 'undefined') {
10471051
if (typeof port !== 'number' && typeof port !== 'string') {
1048-
throw new TypeError('"port" option should be a number or string: ' +
1049-
port);
1052+
throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
1053+
'otions.port',
1054+
['number', 'string'],
1055+
port);
10501056
}
10511057
if (!isLegalPort(port)) {
1052-
throw new RangeError('"port" option should be >= 0 and < 65536: ' + port);
1058+
throw new errors.RangeError('ERR_SOCKET_BAD_PORT');
10531059
}
10541060
}
10551061
port |= 0;
@@ -1065,7 +1071,10 @@ function lookupAndConnect(self, options) {
10651071
}
10661072

10671073
if (options.lookup && typeof options.lookup !== 'function')
1068-
throw new TypeError('"lookup" option should be a function');
1074+
throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
1075+
'options.lookup',
1076+
['function'],
1077+
options.lookup);
10691078

10701079
var dnsopts = {
10711080
family: options.family,
@@ -1207,7 +1216,10 @@ function Server(options, connectionListener) {
12071216
this.on('connection', connectionListener);
12081217
}
12091218
} else {
1210-
throw new TypeError('options must be an object');
1219+
throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
1220+
'options',
1221+
['object'],
1222+
options);
12111223
}
12121224

12131225
this._connections = 0;
@@ -1465,7 +1477,7 @@ Server.prototype.listen = function(...args) {
14651477
var backlog;
14661478
if (typeof options.port === 'number' || typeof options.port === 'string') {
14671479
if (!isLegalPort(options.port)) {
1468-
throw new RangeError('"port" argument must be >= 0 and < 65536');
1480+
throw new errors.RangeError('ERR_SOCKET_BAD_PORT');
14691481
}
14701482
backlog = options.backlog || backlogFromArgs;
14711483
// start TCP server listening on host:port
@@ -1490,7 +1502,9 @@ Server.prototype.listen = function(...args) {
14901502
return this;
14911503
}
14921504

1493-
throw new Error('Invalid listen argument: ' + util.inspect(options));
1505+
throw new errors.TypeError('ERR_INVALID_OPT_VALUE',
1506+
'listen options',
1507+
util.inspect(options));
14941508
};
14951509

14961510
function lookupAndListen(self, port, address, backlog, exclusive) {

test/parallel/test-net-connect-options-port.js

Lines changed: 35 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -27,35 +27,37 @@ const net = require('net');
2727

2828
// Test wrong type of ports
2929
{
30-
function portTypeError(opt) {
31-
const prefix = '"port" option should be a number or string: ';
32-
const cleaned = opt.replace(/[\\^$.*+?()[\]{}|=!<>:-]/g, '\\$&');
33-
return new RegExp(`^TypeError: ${prefix}${cleaned}$`);
30+
function portTypeError() {
31+
return common.expectsError({
32+
code: 'ERR_INVALID_ARG_TYPE',
33+
type: TypeError
34+
});
3435
}
3536

36-
syncFailToConnect(true, portTypeError('true'));
37-
syncFailToConnect(false, portTypeError('false'));
38-
syncFailToConnect([], portTypeError(''), true);
39-
syncFailToConnect({}, portTypeError('[object Object]'), true);
40-
syncFailToConnect(null, portTypeError('null'));
37+
syncFailToConnect(true, portTypeError);
38+
syncFailToConnect(false, portTypeError);
39+
syncFailToConnect([], portTypeError, true);
40+
syncFailToConnect({}, portTypeError, true);
41+
syncFailToConnect(null, portTypeError);
4142
}
4243

4344
// Test out of range ports
4445
{
45-
function portRangeError(opt) {
46-
const prefix = '"port" option should be >= 0 and < 65536: ';
47-
const cleaned = opt.replace(/[\\^$.*+?()[\]{}|=!<>:-]/g, '\\$&');
48-
return new RegExp(`^RangeError: ${prefix}${cleaned}$`);
46+
function portRangeError() {
47+
return common.expectsError({
48+
code: 'ERR_SOCKET_BAD_PORT',
49+
type: RangeError
50+
});
4951
}
5052

51-
syncFailToConnect('', portRangeError(''));
52-
syncFailToConnect(' ', portRangeError(' '));
53-
syncFailToConnect('0x', portRangeError('0x'), true);
54-
syncFailToConnect('-0x1', portRangeError('-0x1'), true);
55-
syncFailToConnect(NaN, portRangeError('NaN'));
56-
syncFailToConnect(Infinity, portRangeError('Infinity'));
57-
syncFailToConnect(-1, portRangeError('-1'));
58-
syncFailToConnect(65536, portRangeError('65536'));
53+
syncFailToConnect('', portRangeError);
54+
syncFailToConnect(' ', portRangeError);
55+
syncFailToConnect('0x', portRangeError, true);
56+
syncFailToConnect('-0x1', portRangeError, true);
57+
syncFailToConnect(NaN, portRangeError);
58+
syncFailToConnect(Infinity, portRangeError);
59+
syncFailToConnect(-1, portRangeError);
60+
syncFailToConnect(65536, portRangeError);
5961
}
6062

6163
// Test invalid hints
@@ -129,33 +131,40 @@ function doConnect(args, getCb) {
129131
];
130132
}
131133

132-
function syncFailToConnect(port, regexp, optOnly) {
134+
function syncFailToConnect(port, assertErr, optOnly) {
133135
if (!optOnly) {
134136
// connect(port, cb) and connect(port)
135137
const portArgBlocks = doConnect([port], () => common.mustNotCall());
136138
for (const block of portArgBlocks) {
137-
assert.throws(block, regexp, `${block.name}(${port})`);
139+
assert.throws(block,
140+
assertErr(),
141+
`${block.name}(${port})`);
138142
}
139143

140144
// connect(port, host, cb) and connect(port, host)
141145
const portHostArgBlocks = doConnect([port, 'localhost'],
142146
() => common.mustNotCall());
143147
for (const block of portHostArgBlocks) {
144-
assert.throws(block, regexp, `${block.name}(${port}, 'localhost')`);
148+
assert.throws(block,
149+
assertErr(),
150+
`${block.name}(${port}, 'localhost')`);
145151
}
146152
}
147153
// connect({port}, cb) and connect({port})
148154
const portOptBlocks = doConnect([{ port }],
149155
() => common.mustNotCall());
150156
for (const block of portOptBlocks) {
151-
assert.throws(block, regexp, `${block.name}({port: ${port}})`);
157+
assert.throws(block,
158+
assertErr(),
159+
`${block.name}({port: ${port}})`);
152160
}
153161

154162
// connect({port, host}, cb) and connect({port, host})
155163
const portHostOptBlocks = doConnect([{ port: port, host: 'localhost' }],
156164
() => common.mustNotCall());
157165
for (const block of portHostOptBlocks) {
158-
assert.throws(block, regexp,
166+
assert.throws(block,
167+
assertErr(),
159168
`${block.name}({port: ${port}, host: 'localhost'})`);
160169
}
161170
}

test/parallel/test-net-localerror.js

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,25 +20,23 @@
2020
// USE OR OTHER DEALINGS IN THE SOFTWARE.
2121

2222
'use strict';
23-
require('../common');
23+
const common = require('../common');
2424
const assert = require('assert');
2525
const net = require('net');
2626

27-
// Using port 0 as localPort / localAddress is already invalid.
2827
connect({
2928
host: 'localhost',
3029
port: 0,
31-
localPort: 'foobar',
32-
}, /^TypeError: "localPort" option should be a number: foobar$/);
30+
localAddress: 'foobar',
31+
}, 'ERR_INVALID_IP_ADDRESS', Error);
3332

3433
connect({
3534
host: 'localhost',
3635
port: 0,
37-
localAddress: 'foobar',
38-
}, /^TypeError: "localAddress" option must be a valid IP: foobar$/);
36+
localPort: 'foobar',
37+
}, 'ERR_INVALID_ARG_TYPE', TypeError);
3938

40-
function connect(opts, msg) {
41-
assert.throws(() => {
42-
net.connect(opts);
43-
}, msg);
39+
function connect(opts, code, type) {
40+
assert.throws(() => net.connect(opts),
41+
common.expectsError({ code: code, type: type }));
4442
}

test/parallel/test-net-options-lookup.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
'use strict';
2-
require('../common');
2+
const common = require('../common');
33
const assert = require('assert');
44
const net = require('net');
55

6-
const expectedError = /^TypeError: "lookup" option should be a function$/;
7-
86
['foobar', 1, {}, []].forEach((input) => connectThrows(input));
97

108
// Using port 0 as lookup is emitted before connecting.
@@ -17,7 +15,10 @@ function connectThrows(input) {
1715

1816
assert.throws(() => {
1917
net.connect(opts);
20-
}, expectedError);
18+
}, common.expectsError({
19+
code: 'ERR_INVALID_ARG_TYPE',
20+
type: TypeError
21+
}));
2122
}
2223

2324
connectDoesNotThrow(() => {});

test/parallel/test-net-server-listen-options.js

Lines changed: 22 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,9 @@
22
const common = require('../common');
33
const assert = require('assert');
44
const net = require('net');
5-
const util = require('util');
65

76
function close() { this.close(); }
87

9-
function listenError(literals, ...values) {
10-
let result = literals[0];
11-
for (const [i, value] of values.entries()) {
12-
const str = util.inspect(value);
13-
// Need to escape special characters.
14-
result += str.replace(/[\\^$.*+?()[\]{}|=!<>:-]/g, '\\$&');
15-
result += literals[i + 1];
16-
}
17-
return new RegExp(`Error: Invalid listen argument: ${result}`);
18-
}
19-
208
{
219
// Test listen()
2210
net.createServer().listen().on('listening', common.mustCall(close));
@@ -36,45 +24,50 @@ const listenOnPort = [
3624
];
3725

3826
{
39-
const portError = /^RangeError: "port" argument must be >= 0 and < 65536$/;
27+
const assertPort = () => {
28+
return common.expectsError({
29+
code: 'ERR_SOCKET_BAD_PORT',
30+
type: Error
31+
});
32+
};
33+
4034
for (const listen of listenOnPort) {
4135
// Arbitrary unused ports
4236
listen('0', common.mustCall(close));
4337
listen(0, common.mustCall(close));
4438
listen(undefined, common.mustCall(close));
4539
listen(null, common.mustCall(close));
4640
// Test invalid ports
47-
assert.throws(() => listen(-1, common.mustNotCall()), portError);
48-
assert.throws(() => listen(NaN, common.mustNotCall()), portError);
49-
assert.throws(() => listen(123.456, common.mustNotCall()), portError);
50-
assert.throws(() => listen(65536, common.mustNotCall()), portError);
51-
assert.throws(() => listen(1 / 0, common.mustNotCall()), portError);
52-
assert.throws(() => listen(-1 / 0, common.mustNotCall()), portError);
41+
assert.throws(() => listen(-1, common.mustNotCall()), assertPort());
42+
assert.throws(() => listen(NaN, common.mustNotCall()), assertPort());
43+
assert.throws(() => listen(123.456, common.mustNotCall()), assertPort());
44+
assert.throws(() => listen(65536, common.mustNotCall()), assertPort());
45+
assert.throws(() => listen(1 / 0, common.mustNotCall()), assertPort());
46+
assert.throws(() => listen(-1 / 0, common.mustNotCall()), assertPort());
5347
}
5448
// In listen(options, cb), port takes precedence over path
5549
assert.throws(() => {
5650
net.createServer().listen({ port: -1, path: common.PIPE },
5751
common.mustNotCall());
58-
}, portError);
52+
}, assertPort());
5953
}
6054

6155
{
62-
function shouldFailToListen(options, optionsInMessage) {
63-
// Plain arguments get normalized into an object before
64-
// formatted in message, options objects don't.
65-
if (arguments.length === 1) {
66-
optionsInMessage = options;
67-
}
56+
function shouldFailToListen(options) {
6857
const block = () => {
6958
net.createServer().listen(options, common.mustNotCall());
7059
};
71-
assert.throws(block, listenError`${optionsInMessage}`,
72-
`expect listen(${util.inspect(options)}) to throw`);
60+
assert.throws(block,
61+
common.expectsError({
62+
code: 'ERR_INVALID_OPT_VALUE',
63+
type: TypeError,
64+
message: /^The value "{.*}" is invalid for option "listen options"$/
65+
}));
7366
}
7467

7568
shouldFailToListen(false, { port: false });
7669
shouldFailToListen({ port: false });
77-
shouldFailToListen(true, { port: true });
70+
shouldFailToListen(true);
7871
shouldFailToListen({ port: true });
7972
// Invalid fd as listen(handle)
8073
shouldFailToListen({ fd: -1 });
Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
11
'use strict';
2-
require('../common');
32
const assert = require('assert');
3+
const common = require('../common');
44
const net = require('net');
55

66
assert.throws(function() { net.createServer('path'); },
7-
/^TypeError: options must be an object$/);
7+
common.expectsError({
8+
code: 'ERR_INVALID_ARG_TYPE',
9+
type: TypeError
10+
}));
11+
812
assert.throws(function() { net.createServer(0); },
9-
/^TypeError: options must be an object$/);
13+
common.expectsError({
14+
code: 'ERR_INVALID_ARG_TYPE',
15+
type: TypeError
16+
}));

test/parallel/test-net-socket-write-error.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
'use strict';
22

3-
require('../common');
3+
const common = require('../common');
44
const assert = require('assert');
55
const net = require('net');
66

77
const server = net.createServer().listen(0, connectToServer);
88

99
function connectToServer() {
1010
const client = net.createConnection(this.address().port, () => {
11-
assert.throws(() => {
12-
client.write(1337);
13-
}, /Invalid data, chunk must be a string or buffer, not number/);
11+
assert.throws(() => client.write(1337),
12+
common.expectsError({
13+
code: 'ERR_INVALID_ARG_TYPE',
14+
type: TypeError
15+
}));
1416

1517
client.end();
1618
})

0 commit comments

Comments
 (0)