Separate error creation logic into its own file (#311)
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 8af8c96 · Browse files · 4 files·+267 added−238 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+267 added−238 removed
- tests:+165 added−158 removed
- other:+102 added−80 removed
Provenance
- Commit
4dd258d- Tree
abe0cf5- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
8af8c96
4 files changed+267 added−238 removed
added:lib/error.js+87 added
1+'use strict';2+const os = require('os');3+const util = require('util');4+5+const getCode = (error, code) => {6+ if (error && error.code) {7+ return [error.code, os.constants.errno[error.code]];8+ }9+10+ if (Number.isInteger(code)) {11+ return [util.getSystemErrorName(-code), code];12+ }13+14+ return [];15+};16+17+const getErrorPrefix = ({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled}) => {18+ if (timedOut) {19+ return `timed out after ${timeout} milliseconds`;20+ }21+22+ if (isCanceled) {23+ return 'was canceled';24+ }25+26+ if (signal) {27+ return `was killed with ${signal}`;28+ }29+30+ if (exitCode !== undefined) {31+ return `failed with exit code ${exitCode} (${exitCodeName})`;32+ }33+34+ return 'failed';35+};36+37+const makeError = ({38+ stdout,39+ stderr,40+ all,41+ error,42+ signal,43+ code,44+ command,45+ timedOut,46+ isCanceled,47+ killed,48+ parsed: {options: {timeout}}49+}) => {50+ const [exitCodeName, exitCode] = getCode(error, code);51+52+ const prefix = getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled});53+ const message = `Command ${prefix}: ${command}`;54+55+ if (error instanceof Error) {56+ error.message = `${message}\n${error.message}`;57+ } else {58+ error = new Error(message);59+ }60+61+ error.command = command;62+ delete error.code;63+ error.exitCode = exitCode;64+ error.exitCodeName = exitCodeName;65+ error.stdout = stdout;66+ error.stderr = stderr;67+68+ if (all !== undefined) {69+ error.all = all;70+ }71+72+ if ('bufferedData' in error) {73+ delete error.bufferedData;74+ }75+76+ error.failed = true;77+ error.timedOut = timedOut;78+ error.isCanceled = isCanceled;79+ error.killed = killed && !timedOut;80+ // `signal` emitted on `spawned.on('exit')` event can be `null`. We normalize81+ // it to `undefined`82+ error.signal = signal || undefined;83+84+ return error;85+};86+87+module.exports = makeError;added:test/error.js+165 added
1+import path from 'path';2+import childProcess from 'child_process';3+import test from 'ava';4+import execa from '..';5+6+process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;7+8+const TIMEOUT_REGEXP = /timed out after/;9+10+const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);11+12+test('stdout/stderr/all available on errors', async t => {13+ const {stdout, stderr, all} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});14+ t.is(typeof stdout, 'string');15+ t.is(typeof stderr, 'string');16+ t.is(typeof all, 'string');17+});18+19+const WRONG_COMMAND = process.platform === 'win32' ?20+ '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.' :21+ '';22+23+test('stdout/stderr/all on process errors', async t => {24+ const {stdout, stderr, all} = await t.throwsAsync(execa('wrong command'));25+ t.is(stdout, '');26+ t.is(stderr, WRONG_COMMAND);27+ t.is(all, WRONG_COMMAND);28+});29+30+test('stdout/stderr/all on process errors, in sync mode', t => {31+ const {stdout, stderr, all} = t.throws(() => {32+ execa.sync('wrong command');33+ });34+ t.is(stdout, '');35+ 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');43+});44+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');49+ t.false(failed);50+});51+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);57+ t.true(failed);58+});59+60+test('error.killed is true if process was killed directly', async t => {61+ const cp = execa('forever');62+63+ cp.kill();64+65+ const {killed} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});66+ t.true(killed);67+});68+69+test('error.killed is false if process was killed indirectly', async t => {70+ const cp = execa('forever');71+72+ process.kill(cp.pid, 'SIGINT');73+74+ // `process.kill()` is emulated by Node.js on Windows75+ const message = process.platform === 'win32' ? /failed with exit code 1/ : /was killed with SIGINT/;76+ const {killed} = await t.throwsAsync(cp, {message});77+ t.false(killed);78+});79+80+test('result.killed is false if not killed', async t => {81+ const {killed} = await execa('noop');82+ t.false(killed);83+});84+85+test('result.killed is false if not killed, in sync mode', t => {86+ const {killed} = execa.sync('noop');87+ t.false(killed);88+});89+90+test('result.killed is false on process error', async t => {91+ const {killed} = await t.throwsAsync(execa('wrong command'));92+ t.false(killed);93+});94+95+test('result.killed is false on process error, in sync mode', t => {96+ const {killed} = t.throws(() => {97+ execa.sync('wrong command');98+ });99+ t.false(killed);100+});101+102+if (process.platform === 'darwin') {103+ test.cb('sanity check: child_process.exec also has killed.false if killed indirectly', t => {104+ const {pid} = childProcess.exec('forever', error => {105+ t.truthy(error);106+ t.false(error.killed);107+ t.end();108+ });109+110+ process.kill(pid, 'SIGINT');111+ });112+}113+114+if (process.platform !== 'win32') {115+ test('error.signal is SIGINT', async t => {116+ const cp = execa('forever');117+118+ process.kill(cp.pid, 'SIGINT');119+120+ const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGINT/});121+ t.is(signal, 'SIGINT');122+ });123+124+ test('error.signal is SIGTERM', async t => {125+ const cp = execa('forever');126+127+ process.kill(cp.pid, 'SIGTERM');128+129+ const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});130+ t.is(signal, 'SIGTERM');131+ });132+133+ test('custom error.signal', async t => {134+ const {signal} = await t.throwsAsync(execa('forever', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));135+ t.is(signal, 'SIGHUP');136+ });137+}138+139+test('result.signal is undefined for successful execution', async t => {140+ const {signal} = await execa('noop');141+ t.is(signal, undefined);142+});143+144+test('result.signal is undefined if process failed, but was not killed', async t => {145+ const {signal} = await t.throwsAsync(execa('exit', [2]), {message: getExitRegExp('2')});146+ t.is(signal, undefined);147+});148+149+const testExitCode = async (t, num) => {150+ const {exitCode} = await t.throwsAsync(execa('exit', [`${num}`]), {message: getExitRegExp(num)});151+ t.is(exitCode, num);152+};153+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');modified:test/test.js-158 removed
1 import path from 'path';2 import fs from 'fs';3 import stream from 'stream';4-import childProcess from 'child_process';4 import test from 'ava';5 import getStream from 'get-stream';6 import isRunning from 'is-running';7 import tempfile from 'tempfile';4 unmodified lines12 process.env.FOO = 'foo';13 14 const TIMEOUT_REGEXP = /timed out after/;15 17-const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);18-16 test('execa()', async t => {17 const {stdout} = await execa('noop', ['foo']);18 t.is(stdout, 'foo');19 });20 unmodified lines40 const {all} = await execa('noop-132');41 t.is(all, '132');42 });43 47-test('stdout/stderr/all available on errors', async t => {48- const {stdout, stderr, all} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});49- t.is(typeof stdout, 'string');50- t.is(typeof stderr, 'string');51- t.is(typeof all, 'string');52-});53-44 test('stdout/stderr/all are undefined if ignored', async t => {45 const {stdout, stderr, all} = await execa('noop', {stdio: 'ignore'});46 t.is(stdout, undefined);47 t.is(stderr, undefined);6 unmodified lines54 t.is(stderr, undefined);55 t.is(all, undefined);56 });57 68-const WRONG_COMMAND = process.platform === 'win32' ?69- '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.' :70- '';71-72-test('stdout/stderr/all on process errors', async t => {73- const {stdout, stderr, all} = await t.throwsAsync(execa('wrong command'));74- t.is(stdout, '');75- t.is(stderr, WRONG_COMMAND);76- t.is(all, WRONG_COMMAND);77-});78-79-test('stdout/stderr/all on process errors, in sync mode', t => {80- const {stdout, stderr, all} = t.throws(() => {81- execa.sync('wrong command');82- });83- t.is(stdout, '');84- t.is(stderr, WRONG_COMMAND);85- t.is(all, undefined);86-});87-58 test('pass `stdout` to a file descriptor', async t => {59 const file = tempfile('.txt');60 await execa('test/fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});61 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');267 unmodified lines329 t.is(result.stderr, undefined);330 t.is(stderr, '.........\n');331 });332 363-test('allow unknown exit code', async t => {364- const {exitCode, exitCodeName} = await t.throwsAsync(execa('exit', ['255']), {message: /exit code 255 \(Unknown system error -255\)/});365- t.is(exitCode, 255);366- t.is(exitCodeName, 'Unknown system error -255');367-});368-369-test('execa() does not return code and failed properties on success', async t => {370- const {exitCode, exitCodeName, failed} = await execa('noop', ['foo']);371- t.is(exitCode, 0);372- t.is(exitCodeName, 'SUCCESS');373- t.false(failed);374-});375-376-test('execa() returns code and failed properties', async t => {377- const {exitCode, exitCodeName, failed} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});378- t.is(exitCode, 2);379- const expectedName = process.platform === 'win32' ? 'Unknown system error -2' : 'ENOENT';380- t.is(exitCodeName, expectedName);381- t.true(failed);382-});383-333 test('use relative path with \'..\' chars', async t => {334 const pathViaParentDir = path.join('..', path.basename(path.dirname(__dirname)), 'test', 'fixtures', 'noop');335 const {stdout} = await execa(pathViaParentDir, ['foo']);336 t.is(stdout, 'foo');9 unmodified lines346 await t.throwsAsync(execa('non-executable', {input: 'Hey!'}), /EACCES/);347 });348 }349 401-test('error.killed is true if process was killed directly', async t => {402- const cp = execa('forever');403-404- cp.kill();405-406- const {killed} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});407- t.true(killed);408-});409-410-test('error.killed is false if process was killed indirectly', async t => {411- const cp = execa('forever');412-413- process.kill(cp.pid, 'SIGINT');414-415- // `process.kill()` is emulated by Node.js on Windows416- const message = process.platform === 'win32' ? /failed with exit code 1/ : /was killed with SIGINT/;417- const {killed} = await t.throwsAsync(cp, {message});418- t.false(killed);419-});420-421-test('result.killed is false if not killed', async t => {422- const {killed} = await execa('noop');423- t.false(killed);424-});425-426-test('result.killed is false if not killed, in sync mode', t => {427- const {killed} = execa.sync('noop');428- t.false(killed);429-});430-431-test('result.killed is false on process error', async t => {432- const {killed} = await t.throwsAsync(execa('wrong command'));433- t.false(killed);434-});435-436-test('result.killed is false on process error, in sync mode', t => {437- const {killed} = t.throws(() => {438- execa.sync('wrong command');439- });440- t.false(killed);441-});442-443-if (process.platform === 'darwin') {444- test.cb('sanity check: child_process.exec also has killed.false if killed indirectly', t => {445- const {pid} = childProcess.exec('forever', error => {446- t.truthy(error);447- t.false(error.killed);448- t.end();449- });450-451- process.kill(pid, 'SIGINT');452- });453-}454-455-if (process.platform !== 'win32') {456- test('error.signal is SIGINT', async t => {457- const cp = execa('forever');458-459- process.kill(cp.pid, 'SIGINT');460-461- const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGINT/});462- t.is(signal, 'SIGINT');463- });464-465- test('error.signal is SIGTERM', async t => {466- const cp = execa('forever');467-468- process.kill(cp.pid, 'SIGTERM');469-470- const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});471- t.is(signal, 'SIGTERM');472- });473-474- test('custom error.signal', async t => {475- const {signal} = await t.throwsAsync(execa('forever', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));476- t.is(signal, 'SIGHUP');477- });478-}479-480-test('result.signal is undefined for successful execution', async t => {481- const {signal} = await execa('noop');482- t.is(signal, undefined);483-});484-485-test('result.signal is undefined if process failed, but was not killed', async t => {486- const {signal} = await t.throwsAsync(execa('exit', [2]), {message: getExitRegExp('2')});487- t.is(signal, undefined);488-});489-490-const testExitCode = async (t, num) => {491- const {exitCode} = await t.throwsAsync(execa('exit', [`${num}`]), {message: getExitRegExp(num)});492- t.is(exitCode, num);493-};494-495-test('error.exitCode is 2', testExitCode, 2);496-test('error.exitCode is 3', testExitCode, 3);497-test('error.exitCode is 4', testExitCode, 4);498-350 test('timeout kills the process if it times out', async t => {351 const {killed, timedOut} = await t.throwsAsync(execa('forever', {timeout: 1, message: TIMEOUT_REGEXP}));352 t.false(killed);353 t.true(timedOut);21 unmodified lines375 const {timedOut} = execa.sync('noop');376 t.false(timedOut);377 });378 528-const errorMessage = async (t, expected, ...args) => {529- await t.throwsAsync(execa('exit', args), {message: expected});530-};531-532-errorMessage.title = (message, expected) => `error.message matches: ${expected}`;533-534-test(errorMessage, /Command failed with exit code 2.*: exit 2 foo bar/, 2, 'foo', 'bar');535-test(errorMessage, /Command failed with exit code 3.*: exit 3 baz quz/, 3, 'baz', 'quz');536-379 const command = async (t, expected, ...args) => {380 const {command: failCommand} = await t.throwsAsync(execa('fail', args));381 t.is(failCommand, `fail${expected}`);382 297 unmodified linesmodified:index.js+15 added-80 removed
1 'use strict';2 const path = require('path');3 const os = require('os');4-const util = require('util');4 const childProcess = require('child_process');5 const crossSpawn = require('cross-spawn');6 const stripFinalNewline = require('strip-final-newline');7 const npmRunPath = require('npm-run-path');1 unmodified line9 const getStream = require('get-stream');10 const mergeStream = require('merge-stream');11 const pFinally = require('p-finally');12 const onExit = require('signal-exit');13+const makeError = require('./lib/error');14 const normalizeStdio = require('./lib/stdio');15 16 const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;17 const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;139 unmodified lines157 ]);158 }159 };160 161-const makeError = (result, options) => {162- const {stdout, stderr, signal} = result;163- let {error} = result;164- const {code, command, timedOut, isCanceled, killed, parsed: {options: {timeout}}} = options;165-166- const [exitCodeName, exitCode] = getCode(result, code);167-168- const prefix = getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled});169- const message = `Command ${prefix}: ${command}`;170-171- if (error instanceof Error) {172- error.message = `${message}\n${error.message}`;173- } else {174- error = new Error(message);175- }176-177- error.command = command;178- delete error.code;179- error.exitCode = exitCode;180- error.exitCodeName = exitCodeName;181- error.stdout = stdout;182- error.stderr = stderr;183-184- if ('all' in result) {185- error.all = result.all;186- }187-188- if ('bufferedData' in error) {189- delete error.bufferedData;190- }191-192- error.failed = true;193- error.timedOut = timedOut;194- error.isCanceled = isCanceled;195- error.killed = killed && !timedOut;196- // `signal` emitted on `spawned.on('exit')` event can be `null`. We normalize197- // it to `undefined`198- error.signal = signal || undefined;199-200- return error;201-};202-203-const getCode = ({error = {}}, code) => {204- if (error.code) {205- return [error.code, os.constants.errno[error.code]];206- }207-208- if (Number.isInteger(code)) {209- return [util.getSystemErrorName(-code), code];210- }211-212- return [];213-};214-215-const getErrorPrefix = ({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled}) => {216- if (timedOut) {217- return `timed out after ${timeout} milliseconds`;218- }219-220- if (isCanceled) {221- return 'was canceled';222- }223-224- if (signal) {225- return `was killed with ${signal}`;226- }227-228- if (exitCode !== undefined) {229- return `failed with exit code ${exitCode} (${exitCodeName})`;230- }231-232- return 'failed';233-};234-161 const joinCommand = (file, args = []) => {162 if (!Array.isArray(args)) {163 return file;164 }132 unmodified lines297 try {298 spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);299 } catch (error) {300 return mergePromise(new childProcess.ChildProcess(), () =>375- Promise.reject(makeError({error, stdout: '', stderr: '', all: ''}, {301+ Promise.reject(makeError({302+ error,303+ stdout: '',304+ stderr: '',305+ all: '',306 command,307 parsed,308 timedOut: false,309 isCanceled: false,21 unmodified lines331 result.stderr = handleOutput(parsed.options, stderr);332 result.all = handleOutput(parsed.options, all);333 334 if (result.error || result.code !== 0 || result.signal !== null) {405- const error = makeError(result, {406- code: result.code,335+ const error = makeError({336+ ...result,337 command,338 parsed,339 timedOut: context.timedOut,340 isCanceled: context.isCanceled,43 unmodified lines384 let result;385 try {386 result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);387 } catch (error) {458- throw makeError({error, stdout: '', stderr: '', all: ''}, {388+ throw makeError({389+ error,390+ stdout: '',391+ stderr: '',392+ all: '',393 command,394 parsed,395 timedOut: false,396 isCanceled: false,4 unmodified lines401 result.stdout = handleOutput(parsed.options, result.stdout, result.error);402 result.stderr = handleOutput(parsed.options, result.stderr, result.error);403 404 if (result.error || result.status !== 0 || result.signal !== null) {471- const error = makeError(result, {405+ const error = makeError({406+ ...result,407 code: result.status,408 command,409 parsed,410 timedOut: result.error && result.error.errno === 'ETIMEDOUT',83 unmodified lines