Fix error properties (#375)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by Sindre Sorhus · parent 39c1968 · Browse files · 9 files·+90 added−105 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+90 added−105 removed
- tests:+42 added−34 removed
- other:+48 added−71 removed
Provenance
- Commit
c1b511b- Tree
c688312- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
39c1968
9 files changed+90 added−105 removed
modified:lib/error.js+16 added-26 removed
12345678910111213141516172345678910261112131415161718193120212223243 unmodified lines28293031433233343536373850394041424344455246474849502 unmodified lines5354555663576558596061627 unmodified lines707172738182837475767778'use strict';const os = require('os');const util = require('util');
const getCode = (error, code) => { if (error && error.code) { return [error.code, os.constants.errno[error.code]]; }
if (Number.isInteger(code)) { return [util.getSystemErrorName(-code), code]; }
return [];};
const getErrorPrefix = ({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled}) => {const getErrorPrefix = ({timedOut, timeout, errorCode, signal, exitCode, isCanceled}) => { if (timedOut) { return `timed out after ${timeout} milliseconds`; }
if (isCanceled) { return 'was canceled'; }
if (signal) { if (errorCode !== undefined) { return `failed with ${errorCode}`; }
if (signal !== undefined) { return `was killed with ${signal}`; }
if (exitCode !== undefined) { return `failed with exit code ${exitCode} (${exitCodeName})`; return `failed with exit code ${exitCode}`; }
return 'failed';};3 unmodified lines stderr, all, error, signal, code, exitCode, command, timedOut, isCanceled, killed, parsed: {options: {timeout}}}) => { const [exitCodeName, exitCode] = getCode(error, code); // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. // We normalize them to `undefined` exitCode = exitCode === null ? undefined : exitCode; signal = signal === null ? undefined : signal;
const errorCode = error && error.code;
const prefix = getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled}); const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, exitCode, isCanceled}); const message = `Command ${prefix}: ${command}`;
if (error instanceof Error) { error.originalMessage = error.message;2 unmodified lines error = new Error(message); }
error.command = command; delete error.code; error.exitCode = exitCode; error.exitCodeName = exitCodeName; error.signal = signal; error.stdout = stdout; error.stderr = stderr;
if (all !== undefined) {7 unmodified lines error.failed = true; error.timedOut = Boolean(timedOut); error.isCanceled = isCanceled; error.killed = killed && !timedOut; // `signal` emitted on `spawned.on('exit')` event can be `null`. We normalize // it to `undefined` error.signal = signal || undefined;
return error;};
module.exports = makeError;modified:lib/promise.js+2 added-2 removed
27 unmodified lines28293031323332333435363715 unmodified lines27 unmodified lines
// Use promises instead of `child_process` eventsconst getSpawnedPromise = spawned => { return new Promise((resolve, reject) => { spawned.on('exit', (code, signal) => { resolve({code, signal}); spawned.on('exit', (exitCode, signal) => { resolve({exitCode, signal}); });
spawned.on('error', error => { reject(error);15 unmodified linesmodified:lib/stream.js+1 added-1 removed
72 unmodified lines73 try {74 return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);75 } catch (error) {76 return Promise.all([77- {error, code: error.code, signal: error.signal, timedOut: error.timedOut},77+ {error, signal: error.signal, timedOut: error.timedOut},78 getBufferedData(stdout, stdoutPromise),79 getBufferedData(stderr, stderrPromise),80 getBufferedData(all, allPromise)81 ]);16 unmodified linesmodified:test/error.js+41 added-33 removed
34 unmodified lines35 t.is(stderr, WRONG_COMMAND);36 t.is(all, undefined);37 });38 39-test('allow unknown exit code', async t => {40- const {exitCode, exitCodeName} = await t.throwsAsync(execa('exit', ['255']), {message: /exit code 255 \(Unknown system error -255\)/});41- t.is(exitCode, 255);42- t.is(exitCodeName, 'Unknown system error -255');39+test('exitCode is 0 on success', async t => {40+ const {exitCode} = await execa('noop', ['foo']);41+ t.is(exitCode, 0);42 });43 45-test('execa() does not return code and failed properties on success', async t => {46- const {exitCode, exitCodeName, failed} = await execa('noop', ['foo']);47- t.is(exitCode, 0);48- t.is(exitCodeName, 'SUCCESS');44+const testExitCode = async (t, num) => {45+ const {exitCode} = await t.throwsAsync(execa('exit', [`${num}`]), {message: getExitRegExp(num)});46+ t.is(exitCode, num);47+};48+49+test('exitCode is 2', testExitCode, 2);50+test('exitCode is 3', testExitCode, 3);51+test('exitCode is 4', testExitCode, 4);52+53+test('error.message contains the command', async t => {54+ await t.throwsAsync(execa('exit', ['2', 'foo', 'bar'], {message: /exit 2 foo bar/}));55+});56+57+test('Original error.message is kept', async t => {58+ const {originalMessage} = await t.throwsAsync(execa('wrong command'));59+ t.is(originalMessage, 'spawn wrong command ENOENT');60+});61+62+test('failed is false on success', async t => {63+ const {failed} = await execa('noop', ['foo']);64 t.false(failed);65 });66 52-test('execa() returns code and failed properties', async t => {53- const {exitCode, exitCodeName, failed} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});54- t.is(exitCode, 2);55- const expectedName = process.platform === 'win32' ? 'Unknown system error -2' : 'ENOENT';56- t.is(exitCodeName, expectedName);67+test('failed is true on failure', async t => {68+ const {failed} = await t.throwsAsync(execa('exit', ['2']));69 t.true(failed);70 });71 72 test('error.killed is true if process was killed directly', async t => {72 unmodified lines145 test('custom error.signal', async t => {146 const {signal} = await t.throwsAsync(execa('noop', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));147 t.is(signal, 'SIGHUP');148 });149+150+ test('exitCode is undefined on signal termination', async t => {151+ const cp = execa('noop');152+153+ process.kill(cp.pid);154+155+ const {exitCode} = await t.throwsAsync(cp);156+ t.is(exitCode, undefined);157+ });158 }159 160 test('result.signal is undefined for successful execution', async t => {161 const {signal} = await execa('noop');4 unmodified lines166 const {signal} = await t.throwsAsync(execa('exit', [2]), {message: getExitRegExp('2')});167 t.is(signal, undefined);168 });169 149-const testExitCode = async (t, num) => {150- const {exitCode} = await t.throwsAsync(execa('exit', [`${num}`]), {message: getExitRegExp(num)});151- t.is(exitCode, num);152-};170+test('error.code is undefined on success', async t => {171+ const {code} = await execa('noop');172+ t.is(code, undefined);173+});174 154-test('error.exitCode is 2', testExitCode, 2);155-test('error.exitCode is 3', testExitCode, 3);156-test('error.exitCode is 4', testExitCode, 4);157-158-const errorMessage = async (t, expected, ...args) => {159- await t.throwsAsync(execa('exit', args), {message: expected});160-};161-162-errorMessage.title = (message, expected) => `error.message matches: ${expected}`;163-164-test(errorMessage, /Command failed with exit code 2.*: exit 2 foo bar/, 2, 'foo', 'bar');165-test(errorMessage, /Command failed with exit code 3.*: exit 3 baz quz/, 3, 'baz', 'quz');166-167-test('Original error message is kept', async t => {168- const {originalMessage} = await t.throwsAsync(execa('wrong command'));169- t.is(originalMessage, 'spawn wrong command ENOENT');175+test('error.code is defined on failure if applicable', async t => {176+ const {code} = await t.throwsAsync(execa('invalid'));177+ t.is(code, 'ENOENT');178 });modified:test/test.js+1 added-1 removed
167 unmodified lines168 try {169 await execa(`fast-exit-${process.platform}`, [], {input: 'data'});170 t.pass();171 } catch (error) {172- t.is(error.exitCode, 32);172+ t.is(error.code, 'EPIPE');173 }174 });175 }176 42 unmodified linesmodified:index.d.ts-5 removed
227 unmodified lines228 */229 exitCode: number;230 231 /**232- The textual exit code of the process that was run.233- */234- exitCodeName: string;235-236- /**232 The output of the process on stdout.233 */234 stdout: StdoutStderrType;235 265 unmodified linesmodified:index.js+12 added-11 removed
102 unmodified lines103 spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));104 spawned.cancel = spawnedCancel.bind(null, spawned, context);105 106 const handlePromise = async () => {107- const [{error, code, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);107+ const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);108 const stdout = handleOutput(parsed.options, stdoutResult);109 const stderr = handleOutput(parsed.options, stderrResult);110 const all = handleOutput(parsed.options, allResult);111 112- if (error || code !== 0 || signal !== null) {112+ if (error || exitCode !== 0 || signal !== null) {113 const returnedError = makeError({114 error,115- code,115+ exitCode,116 signal,117 stdout,118 stderr,119 all,13 unmodified lines133 134 return {135 command,136 exitCode: 0,137- exitCodeName: 'SUCCESS',137 stdout,138 stderr,139 all,140 failed: false,38 unmodified lines179 killed: false180 });181 }182 184- result.stdout = handleOutput(parsed.options, result.stdout, result.error);185- result.stderr = handleOutput(parsed.options, result.stderr, result.error);183+ const stdout = handleOutput(parsed.options, result.stdout, result.error);184+ const stderr = handleOutput(parsed.options, result.stderr, result.error);185 186 if (result.error || result.status !== 0 || result.signal !== null) {187 const error = makeError({189- ...result,190- code: result.status,188+ stdout,189+ stderr,190+ error: result.error,191+ signal: result.signal,192+ exitCode: result.status,193 command,194 parsed,195 timedOut: result.error && result.error.code === 'ETIMEDOUT',196 isCanceled: false,9 unmodified lines206 207 return {208 command,209 exitCode: 0,208- exitCodeName: 'SUCCESS',209- stdout: result.stdout,210- stderr: result.stderr,210+ stdout,211+ stderr,212 failed: false,213 timedOut: false,214 isCanceled: false,215 killed: false40 unmodified linesmodified:index.test-d.ts-4 removed
15 unmodified lines16 17 const unicornsResult = await execaPromise;18 expectType<string>(unicornsResult.command);19 expectType<number>(unicornsResult.exitCode);20- expectType<string>(unicornsResult.exitCodeName);20 expectType<string>(unicornsResult.stdout);21 expectType<string>(unicornsResult.stderr);22 expectType<string | undefined>(unicornsResult.all);23 expectType<boolean>(unicornsResult.failed);5 unmodified lines29 const execaError: ExecaError = error;30 31 expectType<string>(execaError.message);32 expectType<number>(execaError.exitCode);34- expectType<string>(execaError.exitCodeName);33 expectType<string>(execaError.stdout);34 expectType<string>(execaError.stderr);35 expectType<string | undefined>(execaError.all);36 expectType<boolean>(execaError.failed);7 unmodified lines44 try {45 const unicornsResult = execa.sync('unicorns');46 expectType<string>(unicornsResult.command);47 expectType<number>(unicornsResult.exitCode);50- expectType<string>(unicornsResult.exitCodeName);48 expectType<string>(unicornsResult.stdout);49 expectType<string>(unicornsResult.stderr);50 expectError(unicornsResult.all);51 expectType<boolean>(unicornsResult.failed);5 unmodified lines57 const execaError: ExecaSyncError = error;58 59 expectType<string>(execaError.message);60 expectType<number>(execaError.exitCode);64- expectType<string>(execaError.exitCodeName);61 expectType<string>(execaError.stdout);62 expectType<string>(execaError.stderr);63 expectError(execaError.all);64 expectType<boolean>(execaError.failed);118 unmodified linesmodified:readme.md+17 added-22 removed
51 unmodified lines52 53 54 // Catching an error55 try {56- await execa('wrong', ['command']);56+ await execa('unknown', ['command']);57 } catch (error) {58 console.log(error);59 /*60 {61- message: 'Command failed with exit code 2 (ENOENT): wrong command spawn wrong ENOENT',62- errno: -2,63- syscall: 'spawn wrong',64- path: 'wrong',61+ message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',62+ errno: 'ENOENT',63+ code: 'ENOENT',64+ syscall: 'spawn unknown',65+ path: 'unknown',66 spawnargs: ['command'],66- command: 'wrong command',67- exitCode: 2,68- exitCodeName: 'ENOENT',67+ originalMessage: 'spawn unknown ENOENT',68+ command: 'unknown command',69 stdout: '',70 stderr: '',71 all: '',72 failed: true,18 unmodified lines91 })();92 93 // Catching an error with a sync method94 try {95- execa.sync('wrong', ['command']);95+ execa.sync('unknown', ['command']);96 } catch (error) {97 console.log(error);98 /*99 {100- message: 'Command failed with exit code 2 (ENOENT): wrong command spawnSync wrong ENOENT',101- errno: -2,102- syscall: 'spawnSync wrong',103- path: 'wrong',100+ message: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',101+ errno: 'ENOENT',102+ code: 'ENOENT',103+ syscall: 'spawnSync unknown',104+ path: 'unknown',105 spawnargs: ['command'],105- command: 'wrong command',106- exitCode: 2,107- exitCodeName: 'ENOENT',106+ originalMessage: 'spawnSync unknown ENOENT',107+ command: 'unknown command',108 stdout: '',109 stderr: '',110+ all: '',111 failed: true,112 timedOut: false,113 isCanceled: false,114 killed: false104 unmodified lines219 Type: `number`220 221 The numeric exit code of the process that was run.222 222-#### exitCodeName223-224-Type: `string`225-226-The textual exit code of the process that was run.227-223 #### stdout224 225 Type: `string | Buffer`226 328 unmodified lines