From ec49fc822901e1a0deb510a876485f5e94b72866 Mon Sep 17 00:00:00 2001 From: Phillip Johnsen Date: Thu, 31 Mar 2016 22:44:02 +0200 Subject: [PATCH] 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: https://github.com/nodejs/node/pull/5981 Reviewed-By: Brian White Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- lib/net.js | 6 ++++-- test/parallel/test-net-socket-write-error.js | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 test/parallel/test-net-socket-write-error.js diff --git a/lib/net.js b/lib/net.js index dc96526683b147..09c582d9d7a2c4 100644 --- a/lib/net.js +++ b/lib/net.js @@ -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); }; diff --git a/test/parallel/test-net-socket-write-error.js b/test/parallel/test-net-socket-write-error.js new file mode 100644 index 00000000000000..db236be1a5e8f3 --- /dev/null +++ b/test/parallel/test-net-socket-write-error.js @@ -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()); +}