Skip to content

Commit ec49fc8

Browse files
phillipjjasnell
authored andcommitted
net: improve socket.write() error message
Informative error messages are very important for developers and could possibly save hours of debugging and frustration. This improves the error message thrown when writing invalid data into a socket, by communicating what's expected compared to what the developer just tried to write. PR-URL: #5981 Reviewed-By: Brian White <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 8dcb82d commit ec49fc8

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

lib/net.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -619,8 +619,10 @@ Socket.prototype.__defineGetter__('localPort', function() {
619619

620620

621621
Socket.prototype.write = function(chunk, encoding, cb) {
622-
if (typeof chunk !== 'string' && !(chunk instanceof Buffer))
623-
throw new TypeError('Invalid data');
622+
if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) {
623+
throw new TypeError(
624+
'Invalid data, chunk must be a string or buffer, not ' + typeof chunk);
625+
}
624626
return stream.Duplex.prototype.write.apply(this, arguments);
625627
};
626628

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const assert = require('assert');
5+
const net = require('net');
6+
7+
const server = net.createServer().listen(common.PORT, connectToServer);
8+
9+
function connectToServer() {
10+
const client = net.createConnection(common.PORT, () => {
11+
assert.throws(() => {
12+
client.write(1337);
13+
}, /Invalid data, chunk must be a string or buffer, not number/);
14+
15+
client.end();
16+
})
17+
.on('end', () => server.close());
18+
}

0 commit comments

Comments
 (0)