Skip to content
Myr

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

3 files+125 added−43 removed

modified:index.js+81 added-43 removed
126 unmodified lines
127 throw err;128 });129}130131module.exports = (cmd, args, opts) => {131function makeError(result, options) {132 const stdout = result.stdout;133 const stderr = result.stderr;134135 let err = result.error;136 const code = result.code;137 const signal = result.signal;138139 const parsed = options.parsed;140 const joinedCmd = options.joinedCmd;141 const timedOut = options.timedOut || false;142143 if (!err) {144 let output = '';145146 if (Array.isArray(parsed.opts.stdio)) {147 if (parsed.opts.stdio[2] !== 'inherit') {148 output += output.length > 0 ? stderr : `\n${stderr}`;149 }150151 if (parsed.opts.stdio[1] !== 'inherit') {152 output += `\n${stdout}`;153 }154 } else if (parsed.opts.stdio !== 'inherit') {155 output = `\n${stderr}${stdout}`;156 }157158 err = new Error(`Command failed: ${joinedCmd}${output}`);159 err.code = code < 0 ? errname(code) : code;160 }161162 err.stdout = stdout;163 err.stderr = stderr;164 err.failed = true;165 err.signal = signal || null;166 err.cmd = joinedCmd;167 err.timedOut = timedOut;168169 return err;170}171172function joinCmd(cmd, args) {173 let joinedCmd = cmd;174175 if (Array.isArray(args) && args.length > 0) {176 joinedCmd += ' ' + args.join(' ');177 }178179 return joinedCmd;180}181182module.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);187188 let spawned;189 try {190 spawned = childProcess.spawn(parsed.cmd, parsed.args, parsed.opts);
33 unmodified lines
224 });225226 spawned.on('error', err => {227 cleanupTimeout();182 resolve({err});228 resolve({error: err});229 });230231 if (spawned.stdin) {232 spawned.stdin.on('error', err => {233 cleanupTimeout();188 resolve({err});234 resolve({error: err});235 });236 }237 });238
12 unmodified lines
251 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];257212 let err = result.err;213 const code = result.code;214 const signal = result.signal;215258 if (removeExitHandler) {259 removeExitHandler();260 }261220 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 });268224 if (Array.isArray(parsed.opts.stdio)) {225 if (parsed.opts.stdio[2] !== 'inherit') {226 output += output.length > 0 ? stderr : `\n${stderr}`;227 }228229 if (parsed.opts.stdio[1] !== 'inherit') {230 output += `\n${stdout}`;231 }232 } else if (parsed.opts.stdio !== 'inherit') {233 output = `\n${stderr}${stdout}`;234 }235236 err = new Error(`Command failed: ${joinedCmd}${output}`);237 err.code = code < 0 ? errname(code) : code;238 }239269 // 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;273245 err.stdout = stdout;246 err.stderr = stderr;247 err.failed = true;248 err.signal = signal || null;249 err.cmd = joinedCmd;250 err.timedOut = timedOut;251274 if (!parsed.opts.reject) {275 return err;276 }277278 throw err;279 }280281 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 lines
313module.exports.shell = (cmd, opts) => handleShell(module.exports, cmd, opts);314315module.exports.sync = (cmd, args, opts) => {316 const parsed = handleArgs(cmd, args, opts);317 const joinedCmd = joinCmd(cmd, args);318319 if (isStream(parsed.opts.input)) {320 throw new TypeError('The `input` option cannot be a stream in sync mode');321 }322323 const result = childProcess.spawnSync(parsed.cmd, parsed.args, parsed.opts);324 result.code = result.status;325302 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 });331306 result.stdout = handleOutput(parsed.opts, result.stdout);307 result.stderr = handleOutput(parsed.opts, result.stderr);332 if (!parsed.opts.reject) {333 return err;334 }335309 return result;336 throw err;337 }338339 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};349350module.exports.shellSync = (cmd, opts) => handleShell(module.exports.sync, cmd, opts);351
1 unmodified line
modified:readme.md+18 added
53 unmodified lines
54 timedOut: false55 }56 */57});5859// example of catching an error with a sync method60try {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```777879## API
218 unmodified lines
modified:test.js+26 added
102 unmodified lines
103test('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});106107test('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});113114test('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});119120test('execa.shellSync()', t => {121 const {stdout} = m.shellSync('node fixtures/noop foo');122 t.is(stdout, 'foo');123});124125test('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});131132test('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});137138test('stripEof option', async t => {139 const {stdout} = await m('noop', ['foo'], {stripEof: false});140 t.is(stdout, 'foo\n');141});
350 unmodified lines