Skip to content

Commit

Permalink
net: improve socket.write() error message
Browse files Browse the repository at this point in the history
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 <mscdex@mscdex.net>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
phillipj authored and jasnell committed Apr 1, 2016
1 parent 8dcb82d commit ec49fc8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/net.js
Original file line number Diff line number Diff line change
Expand Up @@ -619,8 +619,10 @@ Socket.prototype.__defineGetter__('localPort', function() {


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

Expand Down
18 changes: 18 additions & 0 deletions test/parallel/test-net-socket-write-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';

const common = require('../common');
const assert = require('assert');
const net = require('net');

const server = net.createServer().listen(common.PORT, connectToServer);

function connectToServer() {
const client = net.createConnection(common.PORT, () => {
assert.throws(() => {
client.write(1337);
}, /Invalid data, chunk must be a string or buffer, not number/);

client.end();
})
.on('end', () => server.close());
}

0 comments on commit ec49fc8

Please sign in to comment.