From 2ecc354cb703ef4ce5c5bc2b9bfc15edd56f733c Mon Sep 17 00:00:00 2001 From: oleg Date: Wed, 2 Mar 2016 19:37:36 +0300 Subject: [PATCH] catch cmd errors at spawn + detail error message --- lib/command/spawn.js | 20 +++++++++++++++++++- test/commands/shell.js | 2 +- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/lib/command/spawn.js b/lib/command/spawn.js index 40f614e..e136498 100644 --- a/lib/command/spawn.js +++ b/lib/command/spawn.js @@ -23,6 +23,8 @@ Command.prototype.run = function(params, callback) { stdout = self.collectOut ? '' : null, stderr = self.attachStderr ? '' : null; + callback = _(callback).once(); + if (!params.cmd) return callback(new Error('`cmd` is not set')); if (!params.args) return callback(new Error('`args` is not set')); params.options = params.options || {}; @@ -34,6 +36,16 @@ Command.prototype.run = function(params, callback) { self.emit('stdin', params.cmd + ' ' + params.args.join(' ') + '\n'); } + var extendError = function (err) { + err.message = ( + 'Error while spawn "' + + [params.cmd].concat(params.args || []).join(' ') + '": ' + + err.message + ); + + return err; + }; + cmd.stdout.on('data', function(data) { if (self.emitOut) self.emit('stdout', data); if (self.collectOut) stdout += data; @@ -47,11 +59,17 @@ Command.prototype.run = function(params, callback) { cmd.on('close', function(code) { var err = null; if (code !== 0) { - err = new Error('Spawned command exits with non-zero code: ' + code); + err = extendError( + new Error('Spawned command exits with non-zero code: ' + code) + ); err.stderr = stderr; } callback(err, stdout); }); + cmd.on('error', function(err) { + callback(extendError(err)); + }); + return cmd; }; diff --git a/test/commands/shell.js b/test/commands/shell.js index 49ed5ce..610fbe7 100644 --- a/test/commands/shell.js +++ b/test/commands/shell.js @@ -44,7 +44,7 @@ describe('Shell command', function() { // messages and codes are slightly different across the OSes // e.g. at linux and macos expect(err.message).match( - /^Spawned command exits with non-zero code: \d+/ + /Spawned command exits with non-zero code: \d+/ ); expect(err.stderr).match(/echo1:.*not found/); expect(std.err).equal('');