Enhance error object in sync methods - fixes #98 (#107)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sam Verschueren · committed by Sindre Sorhus · parent dc7e21b · Browse files · 3 files·+125 added−43 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+125 added−43 removed
- other:+125 added−43 removed
Provenance
- Commit
d31cc91- Tree
9aa837e- Author
Sam Verschueren <sam.verschueren@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
dc7e21b
3 files changed+125 added−43 removed
modified:index.js+81 added-43 removed
126 unmodified lines127 throw err;128 });129 }130 131-module.exports = (cmd, args, opts) => {131+function makeError(result, options) {132+ const stdout = result.stdout;133+ const stderr = result.stderr;134+135+ let err = result.error;136+ const code = result.code;137+ const signal = result.signal;138+139+ const parsed = options.parsed;140+ const joinedCmd = options.joinedCmd;141+ const timedOut = options.timedOut || false;142+143+ if (!err) {144+ let output = '';145+146+ if (Array.isArray(parsed.opts.stdio)) {147+ if (parsed.opts.stdio[2] !== 'inherit') {148+ output += output.length > 0 ? stderr : `\n${stderr}`;149+ }150+151+ if (parsed.opts.stdio[1] !== 'inherit') {152+ output += `\n${stdout}`;153+ }154+ } else if (parsed.opts.stdio !== 'inherit') {155+ output = `\n${stderr}${stdout}`;156+ }157+158+ err = new Error(`Command failed: ${joinedCmd}${output}`);159+ err.code = code < 0 ? errname(code) : code;160+ }161+162+ err.stdout = stdout;163+ err.stderr = stderr;164+ err.failed = true;165+ err.signal = signal || null;166+ err.cmd = joinedCmd;167+ err.timedOut = timedOut;168+169+ return err;170+}171+172+function joinCmd(cmd, args) {173 let joinedCmd = cmd;174 175 if (Array.isArray(args) && args.length > 0) {176 joinedCmd += ' ' + args.join(' ');177 }178 179+ return joinedCmd;180+}181+182+module.exports = (cmd, args, opts) => {183 const parsed = handleArgs(cmd, args, opts);184 const encoding = parsed.opts.encoding;185 const maxBuffer = parsed.opts.maxBuffer;186+ const joinedCmd = joinCmd(cmd, args);187 188 let spawned;189 try {190 spawned = childProcess.spawn(parsed.cmd, parsed.args, parsed.opts);33 unmodified lines224 });225 226 spawned.on('error', err => {227 cleanupTimeout();182- resolve({err});228+ resolve({error: err});229 });230 231 if (spawned.stdin) {232 spawned.stdin.on('error', err => {233 cleanupTimeout();188- resolve({err});234+ resolve({error: err});235 });236 }237 });238 12 unmodified lines251 getStream(spawned, 'stdout', encoding, maxBuffer),252 getStream(spawned, 'stderr', encoding, maxBuffer)253 ]).then(arr => {254 const result = arr[0];209- const stdout = arr[1];210- const stderr = arr[2];255+ result.stdout = arr[1];256+ result.stderr = arr[2];257 212- let err = result.err;213- const code = result.code;214- const signal = result.signal;215-258 if (removeExitHandler) {259 removeExitHandler();260 }261 220- if (err || code !== 0 || signal !== null) {221- if (!err) {222- let output = '';262+ if (result.error || result.code !== 0 || result.signal !== null) {263+ const err = makeError(result, {264+ joinedCmd,265+ parsed,266+ timedOut267+ });268 224- if (Array.isArray(parsed.opts.stdio)) {225- if (parsed.opts.stdio[2] !== 'inherit') {226- output += output.length > 0 ? stderr : `\n${stderr}`;227- }228-229- if (parsed.opts.stdio[1] !== 'inherit') {230- output += `\n${stdout}`;231- }232- } else if (parsed.opts.stdio !== 'inherit') {233- output = `\n${stderr}${stdout}`;234- }235-236- err = new Error(`Command failed: ${joinedCmd}${output}`);237- err.code = code < 0 ? errname(code) : code;238- }239-269 // TODO: missing some timeout logic for killed270 // https://github.com/nodejs/node/blob/master/lib/child_process.js#L203271 // err.killed = spawned.killed || killed;272 err.killed = err.killed || spawned.killed;273 245- err.stdout = stdout;246- err.stderr = stderr;247- err.failed = true;248- err.signal = signal || null;249- err.cmd = joinedCmd;250- err.timedOut = timedOut;251-274 if (!parsed.opts.reject) {275 return err;276 }277 278 throw err;279 }280 281 return {260- stdout: handleOutput(parsed.opts, stdout),261- stderr: handleOutput(parsed.opts, stderr),282+ stdout: handleOutput(parsed.opts, result.stdout),283+ stderr: handleOutput(parsed.opts, result.stderr),284 code: 0,285 failed: false,286 killed: false,287 signal: null,25 unmodified lines313 module.exports.shell = (cmd, opts) => handleShell(module.exports, cmd, opts);314 315 module.exports.sync = (cmd, args, opts) => {316 const parsed = handleArgs(cmd, args, opts);317+ const joinedCmd = joinCmd(cmd, args);318 319 if (isStream(parsed.opts.input)) {320 throw new TypeError('The `input` option cannot be a stream in sync mode');321 }322 323 const result = childProcess.spawnSync(parsed.cmd, parsed.args, parsed.opts);324+ result.code = result.status;325 302- if (result.error || result.status !== 0) {303- throw (result.error || new Error(result.stderr === '' ? result.stdout : result.stderr));304- }326+ if (result.error || result.status !== 0 || result.signal !== null) {327+ const err = makeError(result, {328+ joinedCmd,329+ parsed330+ });331 306- result.stdout = handleOutput(parsed.opts, result.stdout);307- result.stderr = handleOutput(parsed.opts, result.stderr);332+ if (!parsed.opts.reject) {333+ return err;334+ }335 309- return result;336+ throw err;337+ }338+339+ return {340+ stdout: handleOutput(parsed.opts, result.stdout),341+ stderr: handleOutput(parsed.opts, result.stderr),342+ code: 0,343+ failed: false,344+ signal: null,345+ cmd: joinedCmd,346+ timedOut: false347+ };348 };349 350 module.exports.shellSync = (cmd, opts) => handleShell(module.exports.sync, cmd, opts);351 1 unmodified linemodified:readme.md+18 added
53 unmodified lines54 timedOut: false55 }56 */57 });58+59+// example of catching an error with a sync method60+try {61+ execa.shellSync('exit 3');62+} catch (err) {63+ console.log(err);64+ /*65+ {66+ message: 'Command failed: /bin/sh -c exit 3'67+ code: 3,68+ signal: null,69+ cmd: '/bin/sh -c exit 3',70+ stdout: '',71+ stderr: '',72+ timedOut: false73+ }74+ */75+}76 ```77 78 79 ## API218 unmodified linesmodified:test.js+26 added
102 unmodified lines103 test('execa.sync() throws error if written to stderr', t => {104 t.throws(() => m.sync('foo'), process.platform === 'win32' ? /'foo' is not recognized as an internal or external command/ : 'spawnSync foo ENOENT');105 });106 107+test('execa.sync() includes stdout and stderr in errors for improved debugging', t => {108+ const err = t.throws(() => m.sync('node', ['fixtures/error-message.js']));109+ t.regex(err.message, /stdout/);110+ t.regex(err.message, /stderr/);111+ t.is(err.code, 1);112+});113+114+test('skip throwing when using reject option in execa.sync()', t => {115+ const err = m.sync('node', ['fixtures/error-message.js'], {reject: false});116+ t.is(typeof err.stdout, 'string');117+ t.is(typeof err.stderr, 'string');118+});119+120 test('execa.shellSync()', t => {121 const {stdout} = m.shellSync('node fixtures/noop foo');122 t.is(stdout, 'foo');123 });124 125+test('execa.shellSync() includes stdout and stderr in errors for improved debugging', t => {126+ const err = t.throws(() => m.shellSync('node fixtures/error-message.js'));127+ t.regex(err.message, /stdout/);128+ t.regex(err.message, /stderr/);129+ t.is(err.code, 1);130+});131+132+test('skip throwing when using reject option in execa.shellSync()', t => {133+ const err = m.shellSync('node fixtures/error-message.js', {reject: false});134+ t.is(typeof err.stdout, 'string');135+ t.is(typeof err.stderr, 'string');136+});137+138 test('stripEof option', async t => {139 const {stdout} = await m('noop', ['foo'], {stripEof: false});140 t.is(stdout, 'foo\n');141 });350 unmodified lines