Skip to content
Myr

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

2 files+75 added−39 removed

modified:index.js+48 added-23 removed
1'use strict';2const path = require('path');3const os = require('os');4const childProcess = require('child_process');5const crossSpawn = require('cross-spawn');6const stripFinalNewline = require('strip-final-newline');7const npmRunPath = require('npm-run-path');
112 unmodified lines
120 });121}122123function makeError(result, options) {123 const {stdout, stderr} = result;124124 const {stdout, stderr, code, signal} = result;125 let {error} = result;126 const {code, signal} = result;126 const {joinedCommand, timedOut, parsed: {options: {timeout}}} = options;127128 const {parsed, joinedCommand} = options;129 const timedOut = options.timedOut || false;128 const [codeString, codeNumber] = getCode(result, code);129131 if (!error) {132 let output = '';133134 if (Array.isArray(parsed.options.stdio)) {135 if (parsed.options.stdio[2] !== 'inherit') {136 output += output.length > 0 ? stderr : `\n${stderr}`;137 }138139 if (parsed.options.stdio[1] !== 'inherit') {140 output += `\n${stdout}`;141 }142 } else if (parsed.options.stdio !== 'inherit') {143 output = `\n${stderr}${stdout}`;144 }145146 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 }134135 const prefix = getErrorPrefix({timedOut, timeout, signal, codeString, codeNumber});136 error.message = `Command ${prefix}: ${error.message}`;137138 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);145146 return error;147}148149function getCode({error = {}}, code) {150 if (error.code) {151 return [error.code, os.constants.errno[error.code]];152 }153154 if (Number.isInteger(code)) {155 return [errname(-Math.abs(code)), Math.abs(code)];156 }157158 return [];159}160161function getErrorPrefix({timedOut, timeout, signal, codeString, codeNumber}) {162 if (timedOut) {163 return `timed out after ${timeout} milliseconds`;164 }165166 if (signal) {167 return `was killed with ${signal}`;168 }169170 if (codeString !== undefined && codeNumber !== undefined) {171 return `failed with exit code ${codeNumber} (${codeString})`;172 }173174 if (codeString !== undefined) {175 return `failed with exit code ${codeString}`;176 }177178 if (codeNumber !== undefined) {179 return `failed with exit code ${codeNumber}`;180 }181182 return 'failed';183}184185function joinCommand(command, args) {186 let joinedCommand = command;187188 if (Array.isArray(args) && args.length > 0) {
174 unmodified lines
modified:test.js+27 added-16 removed
12 unmodified lines
13process.env.FOO = 'foo';1415const NO_NEWLINES_REGEXP = /^[^\n]*$/;16const STDERR_STDOUT_REGEXP = /stderr[^]*stdout/;17const TIMEOUT_REGEXP = /timed out after/;1819function getExitRegExp(exitMessage) {20 return new RegExp(`failed with exit code ${exitMessage}`);21}2223test('execa()', async t => {24 const {stdout} = await m('noop', ['foo']);25 t.is(stdout, 'foo');26});
22 unmodified lines
49 t.is(stderr, 'foo');50});5152test('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 lines
103 t.is(stdout, 'foo');104});105106test('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});109110test('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 lines
260 t.is(typeof error.stdout, 'string');261 t.is(typeof error.stderr, 'string');262});263264test('allow unknown exit code', async t => {265 await t.throwsAsync(m('exit', ['255']), {message: /exit code 255 \(Unknown system error -255\)/});266});267268test('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 lines
292 setTimeout(() => {293 cp.kill();294 }, 100);295287 const error = await t.throwsAsync(cp);296 const error = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});297 t.true(error.killed);298});299300// TODO: Should this really be the case, or should we improve on child_process?
3 unmodified lines
304 setTimeout(() => {305 process.kill(cp.pid, 'SIGINT');306 }, 100);307308 // `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});313314if (process.platform === 'darwin') {
17 unmodified lines
332 setTimeout(() => {333 process.kill(cp.pid, 'SIGINT');334 }, 100);335325 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 });339340 test('error.signal is SIGTERM', async t => {
2 unmodified lines
343 setTimeout(() => {344 process.kill(cp.pid, 'SIGTERM');345 }, 100);346336 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 });350351 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 line
358 t.is((await m('noop')).signal, null);359});360361test('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});365366async 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}369370test('error.code is 2', code, 2);371test('error.code is 3', code, 3);372test('error.code is 4', code, 4);373374test('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}));376377 t.true(error.timedOut);378 t.not(error.code, 22);379});380381test('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});385386test('timedOut will be false if no timeout was set and zero exit code', async t => {
1 unmodified line
388 t.false(result.timedOut);389});390391test('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});395396async function errorMessage(t, expected, ...args) {
1 unmodified line
398}399400errorMessage.title = (message, expected) => `error.message matches: ${expected}`;401391test(errorMessage, /Command failed: exit 2 foo bar/, 2, 'foo', 'bar');392test(errorMessage, /Command failed: exit 3 baz quz/, 3, 'baz', 'quz');402test(errorMessage, /Command failed with exit code 2.*: exit 2 foo bar/, 2, 'foo', 'bar');403test(errorMessage, /Command failed with exit code 3.*: exit 3 baz quz/, 3, 'baz', 'quz');404405async function cmd(t, expected, ...args) {406 const error = await t.throwsAsync(m('fail', args));407 t.is(error.cmd, `fail${expected}`);
55 unmodified lines
463 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