Improve returned `error.message` (#180)
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 eac23b0 · Browse files · 2 files·+75 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+75 added−39 removed
- other:+75 added−39 removed
Provenance
- Commit
1fd9db4- Tree
7a6205c- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
eac23b0
2 files changed+75 added−39 removed
modified:index.js+48 added-23 removed
1 'use strict';2 const path = require('path');3+const os = require('os');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');112 unmodified lines120 });121 }122 123 function makeError(result, options) {123- const {stdout, stderr} = result;124-124+ const {stdout, stderr, code, signal} = result;125 let {error} = result;126- const {code, signal} = result;126+ const {joinedCommand, timedOut, parsed: {options: {timeout}}} = options;127 128- const {parsed, joinedCommand} = options;129- const timedOut = options.timedOut || false;128+ const [codeString, codeNumber] = getCode(result, code);129 131- if (!error) {132- let output = '';133-134- if (Array.isArray(parsed.options.stdio)) {135- if (parsed.options.stdio[2] !== 'inherit') {136- output += output.length > 0 ? stderr : `\n${stderr}`;137- }138-139- if (parsed.options.stdio[1] !== 'inherit') {140- output += `\n${stdout}`;141- }142- } else if (parsed.options.stdio !== 'inherit') {143- output = `\n${stderr}${stdout}`;144- }145-146- error = new Error(`Command failed: ${joinedCommand}${output}`);147- error.code = code < 0 ? errname(code) : code;130+ if (!(error instanceof Error)) {131+ const message = [joinedCommand, stderr, stdout].filter(Boolean).join('\n');132+ error = new Error(message);133 }134 135+ const prefix = getErrorPrefix({timedOut, timeout, signal, codeString, codeNumber});136+ error.message = `Command ${prefix}: ${error.message}`;137+138+ error.code = codeNumber || codeString;139 error.stdout = stdout;140 error.stderr = stderr;141 error.failed = true;142 error.signal = signal || null;143 error.cmd = joinedCommand;155- error.timedOut = timedOut;144+ error.timedOut = Boolean(timedOut);145 146 return error;147 }148 149+function getCode({error = {}}, code) {150+ if (error.code) {151+ return [error.code, os.constants.errno[error.code]];152+ }153+154+ if (Number.isInteger(code)) {155+ return [errname(-Math.abs(code)), Math.abs(code)];156+ }157+158+ return [];159+}160+161+function getErrorPrefix({timedOut, timeout, signal, codeString, codeNumber}) {162+ if (timedOut) {163+ return `timed out after ${timeout} milliseconds`;164+ }165+166+ if (signal) {167+ return `was killed with ${signal}`;168+ }169+170+ if (codeString !== undefined && codeNumber !== undefined) {171+ return `failed with exit code ${codeNumber} (${codeString})`;172+ }173+174+ if (codeString !== undefined) {175+ return `failed with exit code ${codeString}`;176+ }177+178+ if (codeNumber !== undefined) {179+ return `failed with exit code ${codeNumber}`;180+ }181+182+ return 'failed';183+}184+185 function joinCommand(command, args) {186 let joinedCommand = command;187 188 if (Array.isArray(args) && args.length > 0) {174 unmodified linesmodified:test.js+27 added-16 removed
12 unmodified lines13 process.env.FOO = 'foo';14 15 const NO_NEWLINES_REGEXP = /^[^\n]*$/;16 const STDERR_STDOUT_REGEXP = /stderr[^]*stdout/;17+const TIMEOUT_REGEXP = /timed out after/;18 19+function getExitRegExp(exitMessage) {20+ return new RegExp(`failed with exit code ${exitMessage}`);21+}22+23 test('execa()', async t => {24 const {stdout} = await m('noop', ['foo']);25 t.is(stdout, 'foo');26 });22 unmodified lines49 t.is(stderr, 'foo');50 });51 52 test('stdout/stderr available on errors', async t => {48- const err = await t.throwsAsync(m('exit', ['2']));53+ const err = await t.throwsAsync(m('exit', ['2']), {message: getExitRegExp('2')});54 t.is(typeof err.stdout, 'string');55 t.is(typeof err.stderr, 'string');56 });57 45 unmodified lines103 t.is(stdout, 'foo');104 });105 106 test('execa.sync() throws error if written to stderr', t => {102- t.throws(() => m.sync('foo'), process.platform === 'win32' ? /'foo' is not recognized as an internal or external command/ : 'spawnSync foo ENOENT');107+ t.throws(() => m.sync('foo'), process.platform === 'win32' ? /'foo' is not recognized as an internal or external command/ : /spawnSync foo ENOENT/);108 });109 110 test('execa.sync() includes stdout and stderr in errors for improved debugging', t => {111 t.throws(() => m.sync('node', ['fixtures/error-message.js']), {message: STDERR_STDOUT_REGEXP, code: 1});148 unmodified lines260 t.is(typeof error.stdout, 'string');261 t.is(typeof error.stderr, 'string');262 });263 264+test('allow unknown exit code', async t => {265+ await t.throwsAsync(m('exit', ['255']), {message: /exit code 255 \(Unknown system error -255\)/});266+});267+268 test('execa() returns code and failed properties', async t => {269 const {code, failed} = await m('noop', ['foo']);261- const error = await t.throwsAsync(m('exit', ['2']), {code: 2});270+ const error = await t.throwsAsync(m('exit', ['2']), {code: 2, message: getExitRegExp('2')});271 t.is(code, 0);272 t.false(failed);273 t.true(error.failed);274 });17 unmodified lines292 setTimeout(() => {293 cp.kill();294 }, 100);295 287- const error = await t.throwsAsync(cp);296+ const error = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});297 t.true(error.killed);298 });299 300 // TODO: Should this really be the case, or should we improve on child_process?3 unmodified lines304 setTimeout(() => {305 process.kill(cp.pid, 'SIGINT');306 }, 100);307 308+ // `process.kill()` is emulated by Node.js on Windows309+ const message = process.platform === 'win32' ? /failed with exit code 1/ : /was killed with SIGINT/;299- const error = await t.throwsAsync(cp);310+ const error = await t.throwsAsync(cp, {message});311 t.false(error.killed);312 });313 314 if (process.platform === 'darwin') {17 unmodified lines332 setTimeout(() => {333 process.kill(cp.pid, 'SIGINT');334 }, 100);335 325- const error = await t.throwsAsync(cp);336+ const error = await t.throwsAsync(cp, {message: /was killed with SIGINT/});337 t.is(error.signal, 'SIGINT');338 });339 340 test('error.signal is SIGTERM', async t => {2 unmodified lines343 setTimeout(() => {344 process.kill(cp.pid, 'SIGTERM');345 }, 100);346 336- const error = await t.throwsAsync(cp);347+ const error = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});348 t.is(error.signal, 'SIGTERM');349 });350 351 test('custom error.signal', async t => {341- const error = await t.throwsAsync(m('delay', ['3000', '0'], {killSignal: 'SIGHUP', timeout: 1500}));352+ const error = await t.throwsAsync(m('delay', ['3000', '0'], {killSignal: 'SIGHUP', timeout: 1500, message: TIMEOUT_REGEXP}));353 t.is(error.signal, 'SIGHUP');354 });355 }356 1 unmodified line358 t.is((await m('noop')).signal, null);359 });360 361 test('result.signal is null if process failed, but was not killed', async t => {351- const error = await t.throwsAsync(m('exit', [2]));362+ const error = await t.throwsAsync(m('exit', [2]), {message: getExitRegExp('2')});363 t.is(error.signal, null);364 });365 366 async function code(t, num) {356- await t.throwsAsync(m('exit', [`${num}`]), {code: num});367+ await t.throwsAsync(m('exit', [`${num}`]), {code: num, message: getExitRegExp(num)});368 }369 370 test('error.code is 2', code, 2);371 test('error.code is 3', code, 3);372 test('error.code is 4', code, 4);373 374 test('timeout will kill the process early', async t => {364- const error = await t.throwsAsync(m('delay', ['60000', '0'], {timeout: 1500}));375+ const error = await t.throwsAsync(m('delay', ['60000', '0'], {timeout: 1500, message: TIMEOUT_REGEXP}));376 377 t.true(error.timedOut);378 t.not(error.code, 22);379 });380 381 test('timeout will not kill the process early', async t => {371- const error = await t.throwsAsync(m('delay', ['3000', '22'], {timeout: 30000}), {code: 22});382+ const error = await t.throwsAsync(m('delay', ['3000', '22'], {timeout: 30000}), {code: 22, message: getExitRegExp('22')});383 t.false(error.timedOut);384 });385 386 test('timedOut will be false if no timeout was set and zero exit code', async t => {1 unmodified line388 t.false(result.timedOut);389 });390 391 test('timedOut will be false if no timeout was set and non-zero exit code', async t => {381- const error = await t.throwsAsync(m('delay', ['1000', '3']));392+ const error = await t.throwsAsync(m('delay', ['1000', '3']), {message: getExitRegExp('3')});393 t.false(error.timedOut);394 });395 396 async function errorMessage(t, expected, ...args) {1 unmodified line398 }399 400 errorMessage.title = (message, expected) => `error.message matches: ${expected}`;401 391-test(errorMessage, /Command failed: exit 2 foo bar/, 2, 'foo', 'bar');392-test(errorMessage, /Command failed: exit 3 baz quz/, 3, 'baz', 'quz');402+test(errorMessage, /Command failed with exit code 2.*: exit 2 foo bar/, 2, 'foo', 'bar');403+test(errorMessage, /Command failed with exit code 3.*: exit 3 baz quz/, 3, 'baz', 'quz');404 405 async function cmd(t, expected, ...args) {406 const error = await t.throwsAsync(m('fail', args));407 t.is(error.cmd, `fail${expected}`);55 unmodified lines463 try {464 await m(`fast-exit-${process.platform}`, [], {input: 'data'});465 t.pass();466 } catch (error) {456- t.is(error.code, 'EPIPE');467+ t.is(error.code, 32);468 }469 });470 }471 95 unmodified lines