Add `ExecaError` and `ExecaSyncError` classes (#911)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent a29352f · Browse files · 28 files·+634 added−511 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
28 files+634 added−511 removed
- tests:+291 added−271 removed
- other:+343 added−240 removed
Provenance
- Commit
fc01815- Tree
1542e58- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
a29352f
28 files changed+634 added−511 removed
modified:docs/scripts.md+12 added-12 removed
515 unmodified lines516 isCanceled,517 isTerminated,518 // and other error-related properties: code, etc.519 } = await $({timeout: 1})`sleep 2`;520-// file:///home/me/code/execa/lib/kill.js:60521-// reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));522-// ^523-// Error: Command timed out after 1 milliseconds: sleep 2520+// ExecaError: Command timed out after 1 milliseconds: sleep 2524-// Timed out521 // at file:///home/me/Desktop/example.js:2:20526-// timedOut: true,527-// signal: 'SIGTERM',528-// originalMessage: 'Timed out',522+// at ... {523 // shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',524+// originalMessage: '',525 // command: 'sleep 2',526 // escapedCommand: 'sleep 2',532-// exitCode: undefined,527+// cwd: '/path/to/cwd',528+// durationMs: 19.95693,529+// failed: true,530+// timedOut: true,531+// isCanceled: false,532+// isTerminated: true,533+// signal: 'SIGTERM',534 // signalDescription: 'Termination',535 // stdout: '',536 // stderr: '',536-// failed: true,537-// isCanceled: false,538-// isTerminated: false537+// stdio: [undefined, '', ''],538+// pipedFrom: []539 // }540 ```541 542 ### Exit codes262 unmodified linesmodified:lib/exit/code.js+16 added-2 removed
1123453 unmodified lines91011121314151617181920212223242526271428import {DiscardedError} from '../return/error.js';import {DiscardedError} from '../return/cause.js';
export const waitForSuccessfulExit = async exitPromise => { const [exitCode, signal] = await exitPromise;
3 unmodified lines
return [exitCode, signal];};
export const getSyncExitResult = ({error, status: exitCode, signal}) => ({ error: getSyncError(error, exitCode, signal), exitCode, signal,});
const getSyncError = (error, exitCode, signal) => { if (error !== undefined) { return error; }
return isFailedExit(exitCode, signal) ? new DiscardedError() : undefined;};
const isSubprocessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;modified:lib/exit/kill.js+1 added-1 removed
1233456769 unmodified linesimport os from 'node:os';import {setTimeout} from 'node:timers/promises';import {isErrorInstance} from '../return/clone.js';import {isErrorInstance} from '../return/cause.js';
export const normalizeForceKillAfterDelay = forceKillAfterDelay => { if (forceKillAfterDelay === false) { return forceKillAfterDelay;69 unmodified linesmodified:lib/exit/timeout.js+1 added-1 removed
122345614 unmodified linesimport {setTimeout} from 'node:timers/promises';import {DiscardedError} from '../return/error.js';import {DiscardedError} from '../return/cause.js';
export const validateTimeout = ({timeout}) => { if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);14 unmodified linesmodified:lib/pipe/throw.js+1 added
37 unmodified lines383940414243444537 unmodified lines escapedCommand: PIPE_COMMAND_MESSAGE, stdioStreamsGroups, options: sourceOptions, startTime, isSync: false,});
const PIPE_COMMAND_MESSAGE = 'source.pipe(destination)';added:lib/return/cause.js+37 added
12345678910111213141516171819202122232425262728293031323334353637export const getFinalError = (originalError, message, isSync) => { const ErrorClass = isSync ? ExecaSyncError : ExecaError; const options = originalError instanceof DiscardedError ? {} : {cause: originalError}; return new ErrorClass(message, options);};
// Indicates that the error is used only to interrupt control flow, but not in the return valueexport class DiscardedError extends Error {}
// Proper way to set `error.name`: it should be inherited and non-enumerableconst setErrorName = (ErrorClass, value) => { Object.defineProperty(ErrorClass.prototype, 'name', { value, writable: true, enumerable: false, configurable: true, }); Object.defineProperty(ErrorClass.prototype, execaErrorSymbol, { value: true, writable: false, enumerable: false, configurable: false, });};
// Unlike `instanceof`, this works across realmsexport const isExecaError = error => isErrorInstance(error) && execaErrorSymbol in error;
const execaErrorSymbol = Symbol('isExecaError');
export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';
export class ExecaError extends Error {}setErrorName(ExecaError, ExecaError.name);
export class ExecaSyncError extends Error {}setErrorName(ExecaSyncError, ExecaSyncError.name);deleted:lib/return/clone.js-70 removed
1-export const getFinalError = (initialError, message) => {2- const error = createFinalError(initialError, message);3- previousErrors.add(error);4- return error;5-};6-7-const createFinalError = (error, message) => {8- if (!isErrorInstance(error)) {9- return new Error(message);10- }11-12- return previousErrors.has(error)13- ? cloneError(error, message)14- : setErrorMessage(error, message);15-};16-17-export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';18-19-const cloneError = (oldError, newMessage) => {20- const {name, message, stack} = oldError;21- const error = new Error(newMessage);22- error.stack = fixStack(stack, message, newMessage);23- Object.defineProperty(error, 'name', {value: name, enumerable: false, configurable: true, writable: true});24- copyErrorProperties(error, oldError);25- return error;26-};27-28-const copyErrorProperties = (newError, previousError) => {29- for (const propertyName of COPIED_ERROR_PROPERTIES) {30- const descriptor = Object.getOwnPropertyDescriptor(previousError, propertyName);31- if (descriptor !== undefined) {32- Object.defineProperty(newError, propertyName, descriptor);33- }34- }35-};36-37-// Known error properties38-const COPIED_ERROR_PROPERTIES = [39- 'cause',40- 'errors',41- 'code',42- 'errno',43- 'syscall',44- 'path',45- 'dest',46- 'address',47- 'port',48- 'info',49-];50-51-// Sets `error.message`.52-// Fixes `error.stack` not being updated when it has been already accessed, since it is memoized by V8.53-// For example, this happens when calling `stream.destroy(error)`.54-// See https://github.com/nodejs/node/issues/5171555-const setErrorMessage = (error, newMessage) => {56- const {message, stack} = error;57- error.message = newMessage;58- error.stack = fixStack(stack, message, newMessage);59- return error;60-};61-62-const fixStack = (stack, message, newMessage) => stack.includes(newMessage)63- ? stack64- : stack.replace(`: ${message}`, `: ${newMessage}`);65-66-// Two `execa()` calls might return the same error.67-// So we must close those before directly mutating them.68-export const isPreviousError = error => previousErrors.has(error);69-70-const previousErrors = new WeakSet();modified:lib/return/early-error.js+1 added-1 removed
10 unmodified lines11 12 const subprocess = new ChildProcess();13 createDummyStreams(subprocess, stdioStreamsGroups);14 15- const earlyError = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime});15+ const earlyError = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime, isSync: false});16 const promise = handleDummyPromise(earlyError, verboseInfo, options);17 return {subprocess, promise};18 };19 17 unmodified linesmodified:lib/return/error.js+16 added-19 removed
2 unmodified lines3 import {isBinary, binaryToString} from '../utils.js';4 import {fixCwdError} from '../arguments/cwd.js';5 import {escapeLines} from '../arguments/escape.js';6 import {getDurationMs} from './duration.js';7-import {getFinalError, isPreviousError} from './clone.js';7+import {getFinalError, DiscardedError, isExecaError} from './cause.js';8 9 export const makeSuccessResult = ({10 command,11 escapedCommand,24 unmodified lines36 escapedCommand,37 stdioStreamsGroups,38 options,39 startTime,40+ isSync,41 }) => makeError({42 error,43 command,44 escapedCommand,1 unmodified line46 timedOut: false,47 isCanceled: false,48 stdio: Array.from({length: stdioStreamsGroups.length}),49 options,50+ isSync,51 });52 53 export const makeError = ({52- error: rawError,54+ error: originalError,55 command,56 escapedCommand,57 startTime,58 timedOut,2 unmodified lines61 signal: rawSignal,62 stdio,63 all,64 options: {timeoutDuration, timeout = timeoutDuration, cwd},65+ isSync,66 }) => {64- const initialError = rawError instanceof DiscardedError ? undefined : rawError;67 const {exitCode, signal, signalDescription} = normalizeExitPayload(rawExitCode, rawSignal);68 const {originalMessage, shortMessage, message} = createMessages({69 stdio,70 all,69- error: initialError,71+ originalError,72 signal,73 signalDescription,74 exitCode,75 escapedCommand,1 unmodified line77 isCanceled,78 timeout,79 cwd,80 });79- const error = getFinalError(initialError, message);81+ const error = getFinalError(originalError, message, isSync);82 83 error.shortMessage = shortMessage;84 error.originalMessage = originalMessage;85 error.command = command;7 unmodified lines93 error.isTerminated = signal !== undefined;94 error.exitCode = exitCode;95 error.signal = signal;96 error.signalDescription = signalDescription;97+ error.code = error.cause?.code;98 99 error.stdout = stdio[1];100 error.stderr = stdio[2];101 1 unmodified line103 error.all = all;104 }105 106 error.stdio = stdio;104-105- if ('bufferedData' in error) {106- delete error.bufferedData;107- }108-107 error.pipedFrom = [];108 109 return error;110 };111 114-// Indicates that the error is used only to interrupt control flow, but not in the return value115-export class DiscardedError extends Error {}116-112 // `signal` and `exitCode` emitted on `subprocess.on('exit')` event can be `null`.113 // We normalize them to `undefined`114 const normalizeExitPayload = (rawExitCode, rawSignal) => {115 const exitCode = rawExitCode === null ? undefined : rawExitCode;4 unmodified lines120 121 const createMessages = ({122 stdio,123 all,129- error,124+ originalError,125 signal,126 signalDescription,127 exitCode,128 escapedCommand,1 unmodified line130 isCanceled,131 timeout,132 cwd,133 }) => {139- const errorCode = error?.code;134+ const errorCode = originalError?.code;135 const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});141- const originalMessage = getOriginalMessage(error, cwd);136+ const originalMessage = getOriginalMessage(originalError, cwd);137 const newline = originalMessage === '' ? '' : '\n';138 const shortMessage = `${prefix}: ${escapedCommand}${newline}${originalMessage}`;139 const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all];140 const message = [shortMessage, ...messageStdio, ...stdio.slice(3)]26 unmodified lines167 168 return 'Command failed';169 };170 176-const getOriginalMessage = (error, cwd) => {177- if (error === undefined) {171+const getOriginalMessage = (originalError, cwd) => {172+ if (originalError instanceof DiscardedError) {173 return '';174 }175 181- const originalMessage = isPreviousError(error) ? error.originalMessage : String(error?.message ?? error);176+ const originalMessage = isExecaError(originalError)177+ ? originalError.originalMessage178+ : String(originalError?.message ?? originalError);179 return escapeLines(fixCwdError(originalMessage, cwd));180 };181 182 const serializeMessagePart = messagePart => Array.isArray(messagePart)14 unmodified linesmodified:lib/async.js+1 added
97 unmodified lines98 stdio,99 all,100 options,101 startTime,102+ isSync: false,103 })104 : makeSuccessResult({command, escapedCommand, stdio, all, options, startTime});modified:lib/sync.js+11 added-9 removed
2 unmodified lines3 import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';4 import {handleOutput, handleResult} from './return/output.js';5 import {handleInputSync, pipeOutputSync} from './stdio/sync.js';6 import {logEarlyResult} from './verbose/complete.js';7-import {isFailedExit} from './exit/code.js';7+import {getSyncExitResult} from './exit/code.js';8 9 export const execaSync = (rawFile, rawArgs, rawOptions) => {10 const {file, args, command, escapedCommand, startTime, verboseInfo, options, stdioStreamsGroups} = handleSyncArguments(rawFile, rawArgs, rawOptions);11 const result = spawnSubprocessSync({file, args, options, command, escapedCommand, stdioStreamsGroups, startTime});28 unmodified lines40 let syncResult;41 try {42 syncResult = spawnSync(file, args, options);43 } catch (error) {44- return makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime});44+ return makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime, isSync: true});45 }46 47+ const {error, exitCode, signal} = getSyncExitResult(syncResult);48 pipeOutputSync(stdioStreamsGroups, syncResult);49 50 const output = syncResult.output || Array.from({length: 3});51 const stdio = output.map(stdioOutput => handleOutput(options, stdioOutput));51- return getSyncResult(syncResult, {stdio, options, command, escapedCommand, startTime});52+ return getSyncResult({error, exitCode, signal, stdio, options, command, escapedCommand, startTime});53 };54 54-const getSyncResult = ({error, status, signal}, {stdio, options, command, escapedCommand, startTime}) => error !== undefined || isFailedExit(status, signal)55- ? makeError({55+const getSyncResult = ({error, exitCode, signal, stdio, options, command, escapedCommand, startTime}) => error === undefined56+ ? makeSuccessResult({command, escapedCommand, stdio, options, startTime})57+ : makeError({58 error,59 command,60 escapedCommand,59- timedOut: error && error.code === 'ETIMEDOUT',61+ timedOut: error.code === 'ETIMEDOUT',62 isCanceled: false,61- exitCode: status,63+ exitCode,64 signal,65 stdio,66 options,67 startTime,66- })67- : makeSuccessResult({command, escapedCommand, stdio, options, startTime});68+ isSync: true,69+ });modified:test/exit/kill.js+55 added-49 removed
185 unmodified lines186 187 test('.kill(error) propagates error', async t => {188 const subprocess = execa('forever.js');189 const originalMessage = 'test';190- const error = new Error(originalMessage);191- t.true(subprocess.kill(error));192- t.is(await t.throwsAsync(subprocess), error);190+ const cause = new Error(originalMessage);191+ t.true(subprocess.kill(cause));192+ const error = await t.throwsAsync(subprocess);193+ t.is(error.cause, cause);194+ t.true(cause.stack.includes(import.meta.url));195 t.is(error.exitCode, undefined);196 t.is(error.signal, 'SIGTERM');197 t.true(error.isTerminated);198 t.is(error.originalMessage, originalMessage);199 t.true(error.message.includes(originalMessage));200 t.true(error.message.includes('was killed with SIGTERM'));199- t.true(error.stack.includes(import.meta.url));201 });202 203 test('.kill(error) uses killSignal', async t => {204 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});204- const error = new Error('test');205- subprocess.kill(error);206- t.is(await t.throwsAsync(subprocess), error);205+ const cause = new Error('test');206+ subprocess.kill(cause);207+ const error = await t.throwsAsync(subprocess);208+ t.is(error.cause, cause);209 t.is(error.signal, 'SIGINT');210 });211 212 test('.kill(signal, error) uses signal', async t => {213 const subprocess = execa('forever.js');212- const error = new Error('test');213- subprocess.kill('SIGINT', error);214- t.is(await t.throwsAsync(subprocess), error);214+ const cause = new Error('test');215+ subprocess.kill('SIGINT', cause);216+ const error = await t.throwsAsync(subprocess);217+ t.is(error.cause, cause);218 t.is(error.signal, 'SIGINT');219 });220 221 test('.kill(error) is a noop if subprocess already exited', async t => {4 unmodified lines226 });227 228 test('.kill(error) terminates but does not change the error if the subprocess already errored but did not exit yet', async t => {229 const subprocess = execa('forever.js');227- const error = new Error('first');228- subprocess.stdout.destroy(error);230+ const cause = new Error('first');231+ subprocess.stdout.destroy(cause);232 await setImmediate();233 const secondError = new Error('second');234 t.true(subprocess.kill(secondError));232- t.is(await t.throwsAsync(subprocess), error);235+ const error = await t.throwsAsync(subprocess);236+ t.is(error.cause, cause);237 t.is(error.exitCode, undefined);238 t.is(error.signal, 'SIGTERM');239 t.true(error.isTerminated);240 t.false(error.message.includes(secondError.message));241 });242 243 test('.kill(error) twice in a row', async t => {244 const subprocess = execa('forever.js');241- const error = new Error('first');242- subprocess.kill(error);243- const secondError = new Error('second');244- subprocess.kill(secondError);245- t.is(await t.throwsAsync(subprocess), error);246- t.false(error.message.includes(secondError.message));245+ const cause = new Error('first');246+ subprocess.kill(cause);247+ const secondCause = new Error('second');248+ subprocess.kill(secondCause);249+ const error = await t.throwsAsync(subprocess);250+ t.is(error.cause, cause);251+ t.false(error.message.includes(secondCause.message));252 });253 254 test('.kill(error) does not emit the "error" event', async t => {255 const subprocess = execa('forever.js');251- const error = new Error('test');252- subprocess.kill(error);253- t.is(await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]), error);256+ const cause = new Error('test');257+ subprocess.kill(cause);258+ const error = await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]);259+ t.is(error.cause, cause);260 });261 262 test('subprocess errors are handled before spawn', async t => {263 const subprocess = execa('forever.js');258- const error = new Error('test');259- subprocess.emit('error', error);264+ const cause = new Error('test');265+ subprocess.emit('error', cause);266 subprocess.kill();261- const thrownError = await t.throwsAsync(subprocess);262- t.is(thrownError, error);263- t.is(thrownError.exitCode, undefined);264- t.is(thrownError.signal, undefined);265- t.false(thrownError.isTerminated);267+ const error = await t.throwsAsync(subprocess);268+ t.is(error.cause, cause);269+ t.is(error.exitCode, undefined);270+ t.is(error.signal, undefined);271+ t.false(error.isTerminated);272 });273 274 test('subprocess errors are handled after spawn', async t => {275 const subprocess = execa('forever.js');276 await once(subprocess, 'spawn');271- const error = new Error('test');272- subprocess.emit('error', error);277+ const cause = new Error('test');278+ subprocess.emit('error', cause);279 subprocess.kill();274- const thrownError = await t.throwsAsync(subprocess);275- t.is(thrownError, error);276- t.is(thrownError.exitCode, undefined);277- t.is(thrownError.signal, 'SIGTERM');278- t.true(thrownError.isTerminated);280+ const error = await t.throwsAsync(subprocess);281+ t.is(error.cause, cause);282+ t.is(error.exitCode, undefined);283+ t.is(error.signal, 'SIGTERM');284+ t.true(error.isTerminated);285 });286 287 test('subprocess double errors are handled after spawn', async t => {288 const abortController = new AbortController();289 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});290 await once(subprocess, 'spawn');285- const error = new Error('test');286- subprocess.emit('error', error);291+ const cause = new Error('test');292+ subprocess.emit('error', cause);293 await setImmediate();294 abortController.abort();289- const thrownError = await t.throwsAsync(subprocess);290- t.is(thrownError, error);291- t.is(thrownError.exitCode, undefined);292- t.is(thrownError.signal, 'SIGTERM');293- t.true(thrownError.isTerminated);295+ const error = await t.throwsAsync(subprocess);296+ t.is(error.cause, cause);297+ t.is(error.exitCode, undefined);298+ t.is(error.signal, 'SIGTERM');299+ t.true(error.isTerminated);300 });301 302 test('subprocess errors use killSignal', async t => {303 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});304 await once(subprocess, 'spawn');299- const error = new Error('test');300- subprocess.emit('error', error);305+ const cause = new Error('test');306+ subprocess.emit('error', cause);307 subprocess.kill();302- const thrownError = await t.throwsAsync(subprocess);303- t.is(thrownError, error);304- t.true(thrownError.isTerminated);305- t.is(thrownError.signal, 'SIGINT');308+ const error = await t.throwsAsync(subprocess);309+ t.is(error.cause, cause);310+ t.true(error.isTerminated);311+ t.is(error.signal, 'SIGINT');312 });modified:test/exit/timeout.js+4 added-3 removed
66 unmodified lines67 });68 69 test('timedOut is true if the timeout happened after a different error occurred', async t => {70 const subprocess = execa('forever.js', {timeout: 1e3});71- const error = new Error('test');72- subprocess.emit('error', error);73- t.is(await t.throwsAsync(subprocess), error);71+ const cause = new Error('test');72+ subprocess.emit('error', cause);73+ const error = await t.throwsAsync(subprocess);74+ t.is(error.cause, cause);75 t.true(error.timedOut);76 });modified:test/pipe/sequence.js+18 added-18 removed
25 unmodified lines26 test('Source stream error -> destination success', async t => {27 const source = execa('noop-repeat.js');28 const destination = execa('stdin.js');29 const pipePromise = source.pipe(destination);30- const error = new Error('test');31- source.stdout.destroy(error);30+ const cause = new Error('test');31+ source.stdout.destroy(cause);32 33 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));34- t.like(await t.throwsAsync(source), {originalMessage: error.originalMessage, exitCode: 1});34+ t.like(await t.throwsAsync(source), {originalMessage: cause.message, exitCode: 1});35 await destination;36 });37 38 test('Destination stream abort -> source failure', async t => {10 unmodified lines49 test('Destination stream error -> source failure', async t => {50 const source = execa('noop-repeat.js');51 const destination = execa('stdin.js');52 const pipePromise = source.pipe(destination);53- const error = new Error('test');54- destination.stdin.destroy(error);53+ const cause = new Error('test');54+ destination.stdin.destroy(cause);55 56 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));57- t.like(await t.throwsAsync(destination), {originalMessage: error.originalMessage, exitCode: 0});57+ t.like(await t.throwsAsync(destination), {originalMessage: cause.message, exitCode: 0});58 t.like(await t.throwsAsync(source), {exitCode: 1});59 });60 61 test('Source success -> destination success', async t => {128 unmodified lines190 });191 192 test('Source already errored -> failure', async t => {193 const source = execa('noop.js', [foobarString]);194- const error = new Error('test');195- source.stdout.destroy(error);194+ const cause = new Error('test');195+ source.stdout.destroy(cause);196 const destination = execa('stdin.js');197 const pipePromise = source.pipe(destination);198 199 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));200- t.is(await t.throwsAsync(source), error);200+ t.like(await t.throwsAsync(source), {cause});201 t.like(await destination, {stdout: ''});202 });203 204 test('Destination already ended -> ignore source', async t => {20 unmodified lines225 });226 227 test('Destination already errored -> failure', async t => {228 const destination = execa('stdin.js');229- const error = new Error('test');230- destination.stdin.destroy(error);231- t.is(await t.throwsAsync(destination), error);229+ const cause = new Error('test');230+ destination.stdin.destroy(cause);231+ t.like(await t.throwsAsync(destination), {cause});232 const source = execa('noop.js', [foobarString]);233 const pipePromise = source.pipe(destination);234 235 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));14 unmodified lines250 const source = execa('noop.js', ['']);251 const destination = execa('stdin.js');252 const pipePromise = source.pipe(destination);253 254- const sourceError = new Error(foobarString);255- source.emit('error', sourceError);256- const destinationError = new Error('other');257- destination.emit('error', destinationError);254+ const sourceCause = new Error(foobarString);255+ source.emit('error', sourceCause);256+ const destinationCause = new Error('other');257+ destination.emit('error', destinationCause);258 259 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));260- t.like(await t.throwsAsync(source), {originalMessage: sourceError.originalMessage});261- t.like(await t.throwsAsync(destination), {originalMessage: destinationError.originalMessage});260+ t.like(await t.throwsAsync(source), {cause: {originalMessage: sourceCause.originalMessage}});261+ t.like(await t.throwsAsync(destination), {cause: {originalMessage: destinationCause.originalMessage}});262 });263 264 test('Does not need to await individual promises', async t => {265 const source = execa('fail.js');48 unmodified linesadded:test/return/cause.js+158 added
1+import test from 'ava';2+import {execa, execaSync, ExecaError, ExecaSyncError} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {foobarString} from '../helpers/input.js';5+import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';6+7+setFixtureDir();8+9+const testUnusualError = async (t, error, expectedOriginalMessage = String(error)) => {10+ const subprocess = execa('empty.js');11+ subprocess.emit('error', error);12+ const {originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);13+ t.is(originalMessage, expectedOriginalMessage);14+ t.true(shortMessage.includes(expectedOriginalMessage));15+ t.is(message, shortMessage);16+};17+18+test('error instance can be null', testUnusualError, null);19+test('error instance can be false', testUnusualError, false);20+test('error instance can be a string', testUnusualError, 'test');21+test('error instance can be a number', testUnusualError, 0);22+test('error instance can be a BigInt', testUnusualError, 0n);23+test('error instance can be a symbol', testUnusualError, Symbol('test'));24+test('error instance can be a function', testUnusualError, () => {});25+test('error instance can be an array', testUnusualError, ['test', 'test']);26+// eslint-disable-next-line unicorn/error-message27+test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');28+test('error instance can be undefined', testUnusualError, undefined, 'undefined');29+30+test('error instance can be a plain object', async t => {31+ const subprocess = execa('empty.js');32+ subprocess.emit('error', {message: foobarString});33+ await t.throwsAsync(subprocess, {message: new RegExp(foobarString)});34+});35+36+const runAndFail = (t, fixtureName, argument, error) => {37+ const subprocess = execa(fixtureName, [argument]);38+ subprocess.emit('error', error);39+ return t.throwsAsync(subprocess);40+};41+42+const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {43+ const fixtureName = 'empty.js';44+ const firstArgument = 'foo';45+46+ const previousArgument = await getPreviousArgument(t, fixtureName);47+ const previousError = await runAndFail(t, fixtureName, firstArgument, previousArgument);48+ const error = await runAndFail(t, fixtureName, argument, previousError);49+ const message = `Command failed: ${fixtureName} ${argument}\n${foobarString}`;50+51+ t.not(error, previousError);52+ t.is(error.cause, previousError);53+ t.is(error.command, `${fixtureName} ${argument}`);54+ t.is(error.message, message);55+ t.true(error.stack.includes(message));56+ t.is(error.shortMessage, message);57+ t.is(error.originalMessage, foobarString);58+};59+60+test('error instance can be shared', testErrorCopy, () => new Error(foobarString));61+test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));62+test('error string can be shared', testErrorCopy, () => foobarString);63+test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));64+test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');65+66+test('error.cause is not set if error.exitCode is not 0', async t => {67+ const {exitCode, cause} = await t.throwsAsync(execa('fail.js'));68+ t.is(exitCode, 2);69+ t.is(cause, undefined);70+});71+72+test('error.cause is not set if error.isTerminated', async t => {73+ const subprocess = execa('forever.js');74+ subprocess.kill();75+ const {isTerminated, cause} = await t.throwsAsync(subprocess);76+ t.true(isTerminated);77+ t.is(cause, undefined);78+});79+80+test('error.cause is not set if error.timedOut', async t => {81+ const {timedOut, cause} = await t.throwsAsync(execa('forever.js', {timeout: 1}));82+ t.true(timedOut);83+ t.is(cause, undefined);84+});85+86+test('error.cause is set on error event', async t => {87+ const subprocess = execa('empty.js');88+ const error = new Error(foobarString);89+ subprocess.emit('error', error);90+ const {cause} = await t.throwsAsync(subprocess);91+ t.is(cause, error);92+});93+94+test('error.cause is set if error.isCanceled', async t => {95+ const controller = new AbortController();96+ const subprocess = execa('forever.js', {cancelSignal: controller.signal});97+ const error = new Error('test');98+ controller.abort(error);99+ const {isCanceled, isTerminated, cause} = await t.throwsAsync(subprocess);100+ t.true(isCanceled);101+ t.false(isTerminated);102+ t.is(cause.cause, error);103+});104+105+test('error.cause is not set if error.isTerminated with .kill(error)', async t => {106+ const subprocess = execa('forever.js');107+ const error = new Error('test');108+ subprocess.kill(error);109+ const {isTerminated, cause} = await t.throwsAsync(subprocess);110+ t.true(isTerminated);111+ t.is(cause, error);112+});113+114+test('Error is instanceof ExecaError', async t => {115+ await t.throwsAsync(execa('fail.js'), {instanceOf: ExecaError});116+});117+118+test('Early error is instanceof ExecaError', async t => {119+ await t.throwsAsync(getEarlyErrorSubprocess(), {instanceOf: ExecaError});120+});121+122+test('Error is instanceof ExecaSyncError', t => {123+ t.throws(() => {124+ execaSync('fail.js');125+ }, {instanceOf: ExecaSyncError});126+});127+128+test('Early error is instanceof ExecaSyncError', t => {129+ t.throws(() => {130+ getEarlyErrorSubprocessSync();131+ }, {instanceOf: ExecaSyncError});132+});133+134+test('Pipe error is instanceof ExecaError', async t => {135+ await t.throwsAsync(execa('empty.js').pipe(false), {instanceOf: ExecaError});136+});137+138+const assertNameShape = (t, error) => {139+ t.false(Object.hasOwn(error, 'name'));140+ t.true(Object.hasOwn(Object.getPrototypeOf(error), 'name'));141+ t.false(propertyIsEnumerable.call(Object.getPrototypeOf(error), 'name'));142+};143+144+const {propertyIsEnumerable} = Object.prototype;145+146+test('error.name is properly set', async t => {147+ const error = await t.throwsAsync(execa('fail.js'));148+ t.is(error.name, 'ExecaError');149+ assertNameShape(t, error);150+});151+152+test('error.name is properly set - sync', async t => {153+ const error = await t.throws(() => {154+ execaSync('fail.js');155+ });156+ t.is(error.name, 'ExecaSyncError');157+ assertNameShape(t, error);158+});deleted:test/return/clone.js-150 removed
1-import test from 'ava';2-import {execa} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {foobarString} from '../helpers/input.js';5-6-setFixtureDir();7-8-const testUnusualError = async (t, error, expectedOriginalMessage = String(error)) => {9- const subprocess = execa('empty.js');10- subprocess.emit('error', error);11- const {originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);12- t.is(originalMessage, expectedOriginalMessage);13- t.true(shortMessage.includes(expectedOriginalMessage));14- t.is(message, shortMessage);15-};16-17-test('error instance can be null', testUnusualError, null);18-test('error instance can be false', testUnusualError, false);19-test('error instance can be a string', testUnusualError, 'test');20-test('error instance can be a number', testUnusualError, 0);21-test('error instance can be a BigInt', testUnusualError, 0n);22-test('error instance can be a symbol', testUnusualError, Symbol('test'));23-test('error instance can be a function', testUnusualError, () => {});24-test('error instance can be an array', testUnusualError, ['test', 'test']);25-// eslint-disable-next-line unicorn/error-message26-test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');27-test('error instance can be undefined', testUnusualError, undefined, '');28-29-test('error instance can be a plain object', async t => {30- const subprocess = execa('empty.js');31- subprocess.emit('error', {message: foobarString});32- await t.throwsAsync(subprocess, {message: new RegExp(foobarString)});33-});34-35-const runAndFail = (t, fixtureName, argument, error) => {36- const subprocess = execa(fixtureName, [argument]);37- subprocess.emit('error', error);38- return t.throwsAsync(subprocess);39-};40-41-const runAndClone = async (t, initialError) => {42- const previousError = await runAndFail(t, 'empty.js', 'foo', initialError);43- t.is(previousError, initialError);44-45- return runAndFail(t, 'empty.js', 'bar', previousError);46-};47-48-const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {49- const fixtureName = 'empty.js';50- const firstArgument = 'foo';51-52- const previousArgument = await getPreviousArgument(t, fixtureName);53- const previousError = await runAndFail(t, fixtureName, firstArgument, previousArgument);54- const error = await runAndFail(t, fixtureName, argument, previousError);55- const message = `Command failed: ${fixtureName} ${argument}\n${foobarString}`;56-57- t.not(error, previousError);58- t.is(error.command, `${fixtureName} ${argument}`);59- t.is(error.message, message);60- t.true(error.stack.includes(message));61- t.is(error.stack, previousError.stack.replace(firstArgument, argument));62- t.is(error.shortMessage, message);63- t.is(error.originalMessage, foobarString);64-};65-66-test('error instance can be shared', testErrorCopy, () => new Error(foobarString));67-test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));68-test('error string can be shared', testErrorCopy, () => foobarString);69-test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));70-test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');71-72-const testErrorCopyProperty = async (t, propertyName, isCopied) => {73- const propertyValue = 'test';74- const initialError = new Error(foobarString);75- initialError[propertyName] = propertyValue;76-77- const error = await runAndClone(t, initialError);78- t.is(error[propertyName] === propertyValue, isCopied);79-};80-81-test('error.code can be copied', testErrorCopyProperty, 'code', true);82-test('error.errno can be copied', testErrorCopyProperty, 'errno', true);83-test('error.syscall can be copied', testErrorCopyProperty, 'syscall', true);84-test('error.path can be copied', testErrorCopyProperty, 'path', true);85-test('error.dest can be copied', testErrorCopyProperty, 'dest', true);86-test('error.address can be copied', testErrorCopyProperty, 'address', true);87-test('error.port can be copied', testErrorCopyProperty, 'port', true);88-test('error.info can be copied', testErrorCopyProperty, 'info', true);89-test('error.other cannot be copied', testErrorCopyProperty, 'other', false);90-91-test('error.name can be copied', async t => {92- const initialError = new TypeError('test');93- const error = await runAndClone(t, initialError);94- t.deepEqual(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(initialError), 'name'), Object.getOwnPropertyDescriptor(error, 'name'));95-});96-97-test('error.cause can be copied', async t => {98- const initialError = new Error('test', {cause: new Error('innerTest')});99- const error = await runAndClone(t, initialError);100- t.deepEqual(Object.getOwnPropertyDescriptor(initialError, 'cause'), Object.getOwnPropertyDescriptor(error, 'cause'));101-});102-103-test('error.errors can be copied', async t => {104- const initialError = new AggregateError([], 'test');105- const error = await runAndClone(t, initialError);106- t.deepEqual(Object.getOwnPropertyDescriptor(initialError, 'errors'), Object.getOwnPropertyDescriptor(error, 'errors'));107-});108-109-test('error.stack is set even if memoized', async t => {110- const message = 'test';111- const error = new Error(message);112- t.is(typeof error.stack, 'string');113-114- const newMessage = 'newTest';115- error.message = newMessage;116- t.false(error.stack.includes(newMessage));117- error.message = message;118-119- const subprocess = execa('empty.js');120- subprocess.emit('error', error);121- t.is(await t.throwsAsync(subprocess), error);122- t.is(error.message, `Command failed: empty.js\n${message}`);123- t.true(error.stack.startsWith(`Error: ${error.message}`));124-});125-126-test('error.stack is set even if memoized with an unusual error.name', async t => {127- const subprocess = execa('empty.js');128- subprocess.stdin.destroy();129- const error = await t.throwsAsync(subprocess);130- t.is(error.message, 'Command failed with ERR_STREAM_PREMATURE_CLOSE: empty.js\nPremature close');131- t.true(error.stack.startsWith(`Error [ERR_STREAM_PREMATURE_CLOSE]: ${error.message}`));132-});133-134-test('Cloned errors keep the stack trace', async t => {135- const message = 'test';136- const error = new Error(message);137- const stack = error.stack.split('\n').filter(line => line.trim().startsWith('at ')).join('\n');138-139- const subprocess = execa('empty.js');140- subprocess.emit('error', error);141- t.is(await t.throwsAsync(subprocess), error);142-143- const secondSubprocess = execa('empty.js');144- secondSubprocess.emit('error', error);145- const secondError = await t.throwsAsync(secondSubprocess);146- t.not(secondError, error);147- t.is(secondError.message, `Command failed: empty.js\n${message}`);148- t.is(secondError.stack, `Error: Command failed: empty.js\n${message}\n${stack}`);149-});150-modified:test/return/error.js+1 added
45 unmodified lines46 'isTerminated',47 'exitCode',48 'signal',49 'signalDescription',50+ 'code',51 'stdout',52 'stderr',53 'all',54 'stdio',135 unmodified linesmodified:test/stdio/node-stream.js+14 added-13 removed
70 unmodified lines71 return {stream, filePath};72 };73 74 const assertFileStreamError = async (t, subprocess, stream, filePath) => {75- const error = new Error('test');76- stream.destroy(error);75+ const cause = new Error('test');76+ stream.destroy(cause);77 78- t.is(await t.throwsAsync(subprocess), error);78+ const error = await t.throwsAsync(subprocess);79+ t.is(error.cause, cause);80 t.is(error.exitCode, 0);81 t.is(error.signal, undefined);82 83 await rm(filePath);142 unmodified lines226 t.true(waitedForDestroy);227 });228 229 test('Handles custom streams destroy errors on subprocess success', async t => {229- const error = new Error('test');230+ const cause = new Error('test');231 const stream = new Writable({232 destroy(destroyError, done) {232- done(destroyError ?? error);233+ done(destroyError ?? cause);234 },235 });235- const thrownError = await t.throwsAsync(execa('empty.js', {stdout: [stream, 'pipe']}));236- t.is(thrownError, error);236+ const error = await t.throwsAsync(execa('empty.js', {stdout: [stream, 'pipe']}));237+ t.is(error.cause, cause);238 });239 240 const testStreamEarlyExit = async (t, stream, streamName) => {241 await t.throwsAsync(execa('noop.js', {[streamName]: [stream, 'pipe'], uid: -1}));39 unmodified lines281 test('subprocess.stdio[*] is ended when an input stream aborts', testInputStreamAbort, 3);282 283 const testInputStreamError = async (t, fdNumber) => {284 const stream = new PassThrough();284- const error = new Error(foobarString);285- stream.destroy(error);285+ const cause = new Error(foobarString);286+ stream.destroy(cause);287 288 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));288- t.is(await t.throwsAsync(subprocess), error);289+ t.like(await t.throwsAsync(subprocess), {cause});290 t.true(subprocess.stdio[fdNumber].writableEnded);291 };292 293 test('subprocess.stdin is ended when an input stream errors', testInputStreamError, 0);294 test('subprocess.stdio[*] is ended when an input stream errors', testInputStreamError, 3);295 296 const testOutputStreamError = async (t, fdNumber) => {297 const stream = new PassThrough();297- const error = new Error(foobarString);298- stream.destroy(error);298+ const cause = new Error(foobarString);299+ stream.destroy(cause);300 301 const subprocess = execa('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe']));301- t.is(await t.throwsAsync(subprocess), error);302+ t.like(await t.throwsAsync(subprocess), {cause});303 t.true(subprocess.stdio[fdNumber].readableAborted);304 t.is(subprocess.stdio[fdNumber].errored, null);305 };306 3 unmodified linesmodified:test/stdio/pipeline.js+3 added-4 removed
24 unmodified lines25 test('Does not destroy process.stderr on subprocess early errors', testDestroyStandardSpawn, 2);26 27 const testDestroyStandardStream = async (t, fdNumber) => {28 const subprocess = execa('forever.js', getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']));29- const error = new Error('test');30- subprocess.stdio[fdNumber].destroy(error);29+ const cause = new Error('test');30+ subprocess.stdio[fdNumber].destroy(cause);31 subprocess.kill();32- const thrownError = await t.throwsAsync(subprocess);33- t.is(thrownError, error);32+ t.like(await t.throwsAsync(subprocess), {cause});33 t.false(STANDARD_STREAMS[fdNumber].destroyed);34 };35 36 test('Does not destroy process.stdin on stream subprocess errors', testDestroyStandardStream, 0);2 unmodified linesmodified:test/stdio/transform.js+3 added-3 removed
189 unmodified lines190 test('Running generators are canceled on subprocess error', testGeneratorCancel, new Error('test'));191 192 const testGeneratorDestroy = async (t, transform) => {193 const subprocess = execa('forever.js', {stdout: transform});194- const error = new Error('test');195- subprocess.stdout.destroy(error);194+ const cause = new Error('test');195+ subprocess.stdout.destroy(cause);196 subprocess.kill();197- t.is(await t.throwsAsync(subprocess), error);197+ t.like(await t.throwsAsync(subprocess), {cause});198 };199 200 test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));201 test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator);4 unmodified linesmodified:test/stdio/web-stream.js+8 added-8 removed
58 unmodified lines59 test('stderr waits for WritableStream completion', testLongWritableStream, 2);60 test('stdio[*] waits for WritableStream completion', testLongWritableStream, 3);61 62 const testWritableStreamError = async (t, fdNumber) => {63- const error = new Error('foobar');63+ const cause = new Error('foobar');64 const writableStream = new WritableStream({65 start(controller) {66- controller.error(error);66+ controller.error(cause);67 },68 });69- const thrownError = await t.throwsAsync(execa('noop.js', getStdio(fdNumber, writableStream)));70- t.is(thrownError, error);69+ const error = await t.throwsAsync(execa('noop.js', getStdio(fdNumber, writableStream)));70+ t.is(error.cause, cause);71 };72 73 test('stdout option handles errors in WritableStream', testWritableStreamError, 1);74 test('stderr option handles errors in WritableStream', testWritableStreamError, 2);75 test('stdio[*] option handles errors in WritableStream', testWritableStreamError, 3);76 77 const testReadableStreamError = async (t, fdNumber) => {78- const error = new Error('foobar');78+ const cause = new Error('foobar');79 const readableStream = new ReadableStream({80 start(controller) {81- controller.error(error);81+ controller.error(cause);82 },83 });84- const thrownError = await t.throwsAsync(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, readableStream)));85- t.is(thrownError, error);84+ const error = await t.throwsAsync(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, readableStream)));85+ t.is(error.cause, cause);86 };87 88 test('stdin option handles errors in ReadableStream', testReadableStreamError, 0);89 test('stdio[*] option handles errors in ReadableStream', testReadableStreamError, 3);9 unmodified linesmodified:test/stream/no-buffer.js+3 added-3 removed
73 unmodified lines74 75 const testNoBufferStreamError = async (t, fdNumber, all) => {76 const subprocess = execa('noop-fd.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});77 const stream = all ? subprocess.all : subprocess.stdio[fdNumber];78- const error = new Error('test');79- stream.destroy(error);80- t.is(await t.throwsAsync(subprocess), error);78+ const cause = new Error('test');79+ stream.destroy(cause);80+ t.like(await t.throwsAsync(subprocess), {cause});81 };82 83 test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);84 test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);26 unmodified linesmodified:test/stream/subprocess.js+16 added-12 removed
57 unmodified lines58 test('Aborting output stdio[*] should not make the subprocess exit', testStreamOutputAbort, 3);59 60 const testStreamInputDestroy = async (t, fdNumber) => {61 const subprocess = getStreamInputSubprocess(fdNumber);62- const error = new Error('test');63- subprocess.stdio[fdNumber].destroy(error);64- t.is(await t.throwsAsync(subprocess), error);62+ const cause = new Error('test');63+ subprocess.stdio[fdNumber].destroy(cause);64+ const error = await t.throwsAsync(subprocess);65+ t.is(error.cause, cause);66 assertStreamInputError(t, error);67 };68 69 test('Destroying stdin should not make the subprocess exit', testStreamInputDestroy, 0);70 test('Destroying input stdio[*] should not make the subprocess exit', testStreamInputDestroy, 3);71 72 const testStreamOutputDestroy = async (t, fdNumber) => {73 const subprocess = getStreamOutputSubprocess(fdNumber);73- const error = new Error('test');74- subprocess.stdio[fdNumber].destroy(error);75- t.is(await t.throwsAsync(subprocess), error);74+ const cause = new Error('test');75+ subprocess.stdio[fdNumber].destroy(cause);76+ const error = await t.throwsAsync(subprocess);77+ t.is(error.cause, cause);78 assertStreamOutputError(t, fdNumber, error);79 };80 81 test('Destroying stdout should not make the subprocess exit', testStreamOutputDestroy, 1);1 unmodified line83 test('Destroying output stdio[*] should not make the subprocess exit', testStreamOutputDestroy, 3);84 85 const testStreamInputError = async (t, fdNumber) => {86 const subprocess = getStreamInputSubprocess(fdNumber);85- const error = new Error('test');87+ const cause = new Error('test');88 const stream = subprocess.stdio[fdNumber];87- stream.emit('error', error);89+ stream.emit('error', cause);90 stream.end();89- t.is(await t.throwsAsync(subprocess), error);91+ const error = await t.throwsAsync(subprocess);92+ t.is(error.cause, cause);93 assertStreamInputError(t, error);94 };95 96 test('Errors on stdin should not make the subprocess exit', testStreamInputError, 0);97 test('Errors on input stdio[*] should not make the subprocess exit', testStreamInputError, 3);98 99 const testStreamOutputError = async (t, fdNumber) => {100 const subprocess = getStreamOutputSubprocess(fdNumber);98- const error = new Error('test');101+ const cause = new Error('test');102 const stream = subprocess.stdio[fdNumber];100- stream.emit('error', error);101- t.is(await t.throwsAsync(subprocess), error);103+ stream.emit('error', cause);104+ const error = await t.throwsAsync(subprocess);105+ t.is(error.cause, cause);106 assertStreamOutputError(t, fdNumber, error);107 };108 109 test('Errors on stdout should not make the subprocess exit', testStreamOutputError, 1);13 unmodified linesmodified:test/stream/wait.js+8 added-8 removed
164 unmodified lines165 166 // eslint-disable-next-line max-params167 const testStreamError = async (t, streamMethod, stream, fdNumber, useTransform) => {168 const subprocess = execa('empty.js', getStreamStdio(fdNumber, stream, useTransform));169- const error = new Error('test');170- streamMethod({stream, subprocess, fdNumber, error});169+ const cause = new Error('test');170+ streamMethod({stream, subprocess, fdNumber, error: cause});171 172- t.is(await t.throwsAsync(subprocess), error);173- const {exitCode, signal, isTerminated, failed} = error;174- t.is(exitCode, 0);175- t.is(signal, undefined);176- t.false(isTerminated);177- t.true(failed);172+ const error = await t.throwsAsync(subprocess);173+ t.is(error.cause, cause);174+ t.is(error.exitCode, 0);175+ t.is(error.signal, undefined);176+ t.false(error.isTerminated);177+ t.true(error.failed);178 t.true(stream.destroyed);179 };180 181 test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);35 unmodified linesmodified:index.d.ts+119 added-40 removed
482 unmodified lines483 */484 readonly encoding?: EncodingOption;485 486 /**487- If `timeout` is greater than `0`, the subprocess will be [terminated](#killsignal) if it runs for longer than that amount of milliseconds.487+ If `timeout` is greater than `0`, the subprocess will be terminated if it runs for longer than that amount of milliseconds.488 489 @default 0490 */491 readonly timeout?: number;118 unmodified lines610 611 /**612 You can abort the subprocess using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).613 614- When `AbortController.abort()` is called, [`.isCanceled`](https://github.com/sindresorhus/execa#iscanceled) becomes `true`.614+ When `AbortController.abort()` is called, `.isCanceled` becomes `true`.615 616 @example617 ```618 import {execa} from 'execa';18 unmodified lines637 638 export type Options = CommonOptions<false>;639 export type SyncOptions = CommonOptions<true>;640 641-/**642-Result of a subprocess execution. On success this is a plain object. On failure this is also an `Error` instance.643-644-The subprocess fails when:645-- its exit code is not `0`646-- it was terminated with a signal647-- timing out648-- being canceled649-- there's not enough memory or there are already too many subprocesses650-*/651-type ExecaCommonResult<IsSync extends boolean = boolean, OptionsType extends CommonOptions = CommonOptions> = {641+declare abstract class CommonResult<642+ IsSync extends boolean = boolean,643+ OptionsType extends CommonOptions = CommonOptions,644+> {645 /**646 The file and arguments that were run, for logging purposes.647 648 This is not escaped and should not be executed directly as a subprocess, including using `execa()` or `execaCommand()`.12 unmodified lines661 662 /**663 The numeric exit code of the subprocess that was run.664 672- This is `undefined` when the subprocess could not be spawned or was terminated by a [signal](#signal).665+ This is `undefined` when the subprocess could not be spawned or was terminated by a signal.666 */667 exitCode?: number;668 669 /**81 unmodified lines751 752 This array is initially empty and is populated each time the `.pipe()` method resolves.753 */754 pipedFrom: IfAsync<IsSync, ExecaResult[], []>;762- // Workaround for a TypeScript bug: https://github.com/microsoft/TypeScript/issues/57062763-} & {};755 765-export type ExecaResult<OptionsType extends Options = Options> = ExecaCommonResult<false, OptionsType> & ErrorUnlessReject<OptionsType['reject']>;766-export type ExecaSyncResult<OptionsType extends SyncOptions = SyncOptions> = ExecaCommonResult<true, OptionsType> & ErrorUnlessReject<OptionsType['reject']>;767-768-type ErrorUnlessReject<RejectOption extends CommonOptions['reject']> = RejectOption extends false769- ? Partial<ExecaCommonError>770- : {};771-772-type ExecaCommonError = {756 /**757 Error message when the subprocess failed to run. In addition to the underlying error message, it also contains some information related to why the subprocess errored.758 759 The subprocess `stderr`, `stdout` and other file descriptors' output are appended to the end, separated with newlines and not interleaved.760 */778- message: string;761+ message?: string;762 763 /**764 This is the same as the `message` property except it does not include the subprocess `stdout`/`stderr`/`stdio`.765 */783- shortMessage: string;766+ shortMessage?: string;767 768 /**769 Original error message. This is the same as the `message` property excluding the subprocess `stdout`/`stderr`/`stdio` and some additional information added by Execa.770 788- This is `undefined` unless the subprocess exited due to an `error` event or a timeout.771+ This exists only if the subprocess exited due to an `error` event or a timeout.772 */773 originalMessage?: string;791-} & Error;774 793-export type ExecaError<OptionsType extends Options = Options> = ExecaCommonResult<false, OptionsType> & ExecaCommonError;794-export type ExecaSyncError<OptionsType extends SyncOptions = SyncOptions> = ExecaCommonResult<true, OptionsType> & ExecaCommonError;775+ /**776+ Underlying error, if there is one. For example, this is set by `.kill(error)`.777 778+ This is usually an `Error` instance.779+ */780+ cause?: unknown;781+782+ /**783+ Node.js-specific [error code](https://nodejs.org/api/errors.html#errorcode), when available.784+ */785+ code?: string;786+787+ // We cannot `extend Error` because `message` must be optional. So we copy its types here.788+ readonly name?: Error['name'];789+ stack?: Error['stack'];790+}791+792+type CommonResultInstance<793+ IsSync extends boolean = boolean,794+ OptionsType extends CommonOptions = CommonOptions,795+> = InstanceType<typeof CommonResult<IsSync, OptionsType>>;796+797+type SuccessResult<798+ IsSync extends boolean = boolean,799+ OptionsType extends CommonOptions = CommonOptions,800+> = CommonResultInstance<IsSync, OptionsType> & OmitErrorIfReject<OptionsType['reject']>;801+802+type OmitErrorIfReject<RejectOption extends CommonOptions['reject']> = RejectOption extends false803+ ? {}804+ : {[ErrorProperty in ErrorProperties]: never};805+806+type ErrorProperties =807+ | 'name'808+ | 'message'809+ | 'stack'810+ | 'cause'811+ | 'shortMessage'812+ | 'originalMessage'813+ | 'code';814+815+/**816+Result of a subprocess execution.817+818+When the subprocess fails, it is rejected with an `ExecaError` instead.819+*/820+export type ExecaResult<OptionsType extends Options = Options> = SuccessResult<false, OptionsType>;821+822+/**823+Result of a subprocess execution.824+825+When the subprocess fails, it is rejected with an `ExecaError` instead.826+*/827+export type ExecaSyncResult<OptionsType extends SyncOptions = SyncOptions> = SuccessResult<true, OptionsType>;828+829+declare abstract class CommonError<830+ IsSync extends boolean = boolean,831+ OptionsType extends CommonOptions = CommonOptions,832+> extends CommonResult<IsSync, OptionsType> {833+ readonly name: NonNullable<CommonResult['name']>;834+ message: NonNullable<CommonResult['message']>;835+ stack: NonNullable<CommonResult['stack']>;836+ shortMessage: NonNullable<CommonResult['shortMessage']>;837+ originalMessage: NonNullable<CommonResult['originalMessage']>;838+}839+840+/**841+Exception thrown when the subprocess fails, either:842+- its exit code is not `0`843+- it was terminated with a signal, including `.kill()`844+- timing out845+- being canceled846+- there's not enough memory or there are already too many subprocesses847+848+This has the same shape as successful results, with a few additional properties.849+*/850+export class ExecaError<OptionsType extends Options = Options> extends CommonError<false, OptionsType> {851+ readonly name: 'ExecaError';852+}853+854+/**855+Exception thrown when the subprocess fails, either:856+- its exit code is not `0`857+- it was terminated with a signal, including `.kill()`858+- timing out859+- being canceled860+- there's not enough memory or there are already too many subprocesses861+862+This has the same shape as successful results, with a few additional properties.863+*/864+export class ExecaSyncError<OptionsType extends SyncOptions = SyncOptions> extends CommonError<true, OptionsType> {865+ readonly name: 'ExecaSyncError';866+}867+868 type StreamUnlessIgnored<869 FdNumber extends string,870 OptionsType extends Options = Options,871 > = SubprocessStream<FdNumber, IgnoresStreamResult<FdNumber, OptionsType>, OptionsType>;117 unmodified lines989 Sends a [signal](https://nodejs.org/api/os.html#signal-constants) to the subprocess. The default signal is the `killSignal` option. `killSignal` defaults to `SIGTERM`, which terminates the subprocess.990 991 This returns `false` when the signal could not be sent, for example when the subprocess has already exited.992 921- When an error is passed as argument, its message and stack trace are kept in the subprocess' error. The subprocess is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).993+ When an error is passed as argument, it is set to the subprocess' `error.cause`. The subprocess is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).994 995 [More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)996 */997 kill(signal: Parameters<ChildProcess['kill']>[0], error?: Error): ReturnType<ChildProcess['kill']>;80 unmodified lines1078 await execa('unknown', ['command']);1079 } catch (error) {1080 console.log(error);1081 /*1010- {1011- message: 'Command failed with ENOENT: unknown command\nspawn unknown ENOENT',1012- errno: -2,1013- code: 'ENOENT',1014- syscall: 'spawn unknown',1015- path: 'unknown',1016- spawnargs: ['command'],1082+ ExecaError: Command failed with ENOENT: unknown command1083+ spawn unknown ENOENT1084+ at ...1085+ at ... {1086 shortMessage: 'Command failed with ENOENT: unknown command\nspawn unknown ENOENT',1087 originalMessage: 'spawn unknown ENOENT',1088 command: 'unknown command',1089 escapedCommand: 'unknown command',2 unmodified lines1092 failed: true,1093 timedOut: false,1094 isCanceled: false,1095 isTerminated: false,1096+ code: 'ENOENT',1097 stdout: '',1098 stderr: '',1099 stdio: [undefined, '', ''],1100 pipedFrom: []1101+ [cause]: Error: spawn unknown ENOENT1102+ at ...1103+ at ... {1104+ errno: -2,1105+ code: 'ENOENT',1106+ syscall: 'spawn unknown',1107+ path: 'unknown',1108+ spawnargs: [ 'command' ]1109+ }1110 }1111 \*\/1112 }1113 ```133 unmodified lines1247 command: string,1248 options?: OptionsType1249 ): ExecaSyncResult<OptionsType>;1250 1172-type TemplateExpression = string | number | ExecaCommonResult1173-| Array<string | number | ExecaCommonResult>;1251+type TemplateExpression = string | number | CommonResultInstance1252+| Array<string | number | CommonResultInstance>;1253 1254 type Execa$<OptionsType extends CommonOptions = {}> = {1255 /**1256 Returns a new instance of `$` but with different default `options`. Consecutive calls are merged to previous ones.221 unmodified linesmodified:index.js+1 added
1 unmodified line2 export {execaSync} from './lib/sync.js';3 export {execaCommand, execaCommandSync} from './lib/command.js';4 export {execaNode} from './lib/arguments/node.js';5 export {$} from './lib/script.js';6+export {ExecaError, ExecaSyncError} from './lib/return/cause.js';modified:index.test-d.ts+56 added-45 removed
10 unmodified lines11 execaSync,12 execaCommand,13 execaCommandSync,14 execaNode,15+ ExecaError,16+ ExecaSyncError,17 type Options,18 type ExecaResult,19 type ExecaSubprocess,18- type ExecaError,20 type SyncOptions,21 type ExecaSyncResult,21- type ExecaSyncError,22 } from './index.js';23 24 const fileUrl = new URL('file:///test');25 549 unmodified lines575 expectType<string>(falseFalseObjectTransformResult.stderr);576 expectType<string>(falseFalseObjectTransformResult.all);577 expectType<[undefined, string, string]>(falseFalseObjectTransformResult.stdio);578 } catch (error: unknown) {579- const execaError = error as ExecaError;579+ if (error instanceof ExecaError) {580+ expectAssignable<ExecaError>(error);581+ expectType<'ExecaError'>(error.name);582+ expectType<string>(error.message);583+ expectType<number | undefined>(error.exitCode);584+ expectType<boolean>(error.failed);585+ expectType<boolean>(error.timedOut);586+ expectType<boolean>(error.isCanceled);587+ expectType<boolean>(error.isTerminated);588+ expectType<string | undefined>(error.signal);589+ expectType<string | undefined>(error.signalDescription);590+ expectType<string>(error.cwd);591+ expectType<number>(error.durationMs);592+ expectType<string>(error.shortMessage);593+ expectType<string>(error.originalMessage);594+ expectType<string | undefined>(error.code);595+ expectType<unknown>(error.cause);596+ expectType<ExecaResult[]>(error.pipedFrom);597+ }598 581- expectType<string>(execaError.message);582- expectType<number | undefined>(execaError.exitCode);583- expectType<boolean>(execaError.failed);584- expectType<boolean>(execaError.timedOut);585- expectType<boolean>(execaError.isCanceled);586- expectType<boolean>(execaError.isTerminated);587- expectType<string | undefined>(execaError.signal);588- expectType<string | undefined>(execaError.signalDescription);589- expectType<string>(execaError.cwd);590- expectType<number>(execaError.durationMs);591- expectType<string>(execaError.shortMessage);592- expectType<string | undefined>(execaError.originalMessage);593- expectType<ExecaResult[]>(execaError.pipedFrom);594-595- expectType<undefined>(execaError.stdio[0]);596-599 const noAllError = error as ExecaError<{}>;600+ expectType<undefined>(noAllError.stdio[0]);601 expectType<undefined>(noAllError.all);602 603 const execaStringError = error as ExecaError<{all: true}>;604 expectType<string>(execaStringError.stdout);107 unmodified lines712 expectType<[undefined, string, string]>(falseObjectTransformStdioError.stdio);713 }714 715 const rejectsResult = await execa('unicorns');713-expectError(rejectsResult.stack);714-expectError(rejectsResult.message);715-expectError(rejectsResult.shortMessage);716-expectError(rejectsResult.originalMessage);716+expectError(rejectsResult.stack?.toString());717+expectError(rejectsResult.message?.toString());718+expectError(rejectsResult.shortMessage?.toString());719+expectError(rejectsResult.originalMessage?.toString());720+expectError(rejectsResult.code?.toString());721+expectError(rejectsResult.cause?.valueOf());722 723 const noRejectsResult = await execa('unicorns', {reject: false});724 expectType<string | undefined>(noRejectsResult.stack);725 expectType<string | undefined>(noRejectsResult.message);726 expectType<string | undefined>(noRejectsResult.shortMessage);727 expectType<string | undefined>(noRejectsResult.originalMessage);728+expectType<string | undefined>(noRejectsResult.code);729+expectType<unknown>(noRejectsResult.cause);730 731 try {732 const unicornsResult = execaSync('unicorns');733 67 unmodified lines801 expectType<string>(numberStderrResult.stdout);802 expectType<undefined>(numberStderrResult.stderr);803 expectError(numberStderrResult.all.toString());804 } catch (error: unknown) {798- const execaError = error as ExecaSyncError;805+ if (error instanceof ExecaSyncError) {806+ expectAssignable<ExecaSyncError>(error);807+ expectType<'ExecaSyncError'>(error.name);808+ expectType<string>(error.message);809+ expectType<number | undefined>(error.exitCode);810+ expectType<boolean>(error.failed);811+ expectType<boolean>(error.timedOut);812+ expectType<boolean>(error.isCanceled);813+ expectType<boolean>(error.isTerminated);814+ expectType<string | undefined>(error.signal);815+ expectType<string | undefined>(error.signalDescription);816+ expectType<string>(error.cwd);817+ expectType<number>(error.durationMs);818+ expectType<string>(error.shortMessage);819+ expectType<string>(error.originalMessage);820+ expectType<string | undefined>(error.code);821+ expectType<unknown>(error.cause);822+ expectType<[]>(error.pipedFrom);823+ }824 800- expectType<ExecaSyncError>(execaError);801- expectType<string>(execaError.message);802- expectType<number | undefined>(execaError.exitCode);803- expectType<boolean>(execaError.failed);804- expectType<boolean>(execaError.timedOut);805- expectType<boolean>(execaError.isCanceled);806- expectType<boolean>(execaError.isTerminated);807- expectType<string | undefined>(execaError.signal);808- expectType<string | undefined>(execaError.signalDescription);809- expectType<string>(execaError.cwd);810- expectType<number>(execaError.durationMs);811- expectType<string>(execaError.shortMessage);812- expectType<string | undefined>(execaError.originalMessage);813- expectType<[]>(execaError.pipedFrom);814-815- expectType<undefined>(execaError.stdio[0]);816-825 const execaStringError = error as ExecaSyncError<{}>;826+ expectType<undefined>(execaStringError.stdio[0]);827 expectType<string>(execaStringError.stdout);828 expectType<string>(execaStringError.stdio[1]);829 expectType<string>(execaStringError.stderr);830 expectType<string>(execaStringError.stdio[2]);49 unmodified lines880 expectError(numberStderrError.all.toString());881 }882 883 const rejectsSyncResult = execaSync('unicorns');875-expectError(rejectsSyncResult.stack);876-expectError(rejectsSyncResult.message);877-expectError(rejectsSyncResult.shortMessage);878-expectError(rejectsSyncResult.originalMessage);884+expectError(rejectsSyncResult.stack?.toString());885+expectError(rejectsSyncResult.message?.toString());886+expectError(rejectsSyncResult.shortMessage?.toString());887+expectError(rejectsSyncResult.originalMessage?.toString());888+expectError(rejectsSyncResult.code?.toString());889+expectError(rejectsSyncResult.cause?.valueOf());890 891 const noRejectsSyncResult = execaSync('unicorns', {reject: false});892 expectType<string | undefined>(noRejectsSyncResult.stack);893 expectType<string | undefined>(noRejectsSyncResult.message);708 unmodified linesmodified:readme.md+70 added-40 removed
217 unmodified lines218 await execa('unknown', ['command']);219 } catch (error) {220 console.log(error);221 /*222- {223- message: 'Command failed with ENOENT: unknown command\nspawn unknown ENOENT',224- errno: -2,225- code: 'ENOENT',226- syscall: 'spawn unknown',227- path: 'unknown',228- spawnargs: ['command'],222+ ExecaError: Command failed with ENOENT: unknown command223+ spawn unknown ENOENT224+ at ...225+ at ... {226 shortMessage: 'Command failed with ENOENT: unknown command\nspawn unknown ENOENT',227 originalMessage: 'spawn unknown ENOENT',228 command: 'unknown command',229 escapedCommand: 'unknown command',2 unmodified lines232 failed: true,233 timedOut: false,234 isCanceled: false,235 isTerminated: false,236+ code: 'ENOENT',237 stdout: '',238 stderr: '',239 stdio: [undefined, '', ''],240 pipedFrom: []241+ [cause]: Error: spawn unknown ENOENT242+ at ...243+ at ... {244+ errno: -2,245+ code: 'ENOENT',246+ syscall: 'spawn unknown',247+ path: 'unknown',248+ spawnargs: [ 'command' ]249+ }250 }251 */252 }253 ```109 unmodified lines363 `arguments`: `string[]`\364 `options`: [`Options`](#options-1) and [`PipeOptions`](#pipeoptions)\365 _Returns_: [`Promise<SubprocessResult>`](#subprocessresult)366 360-[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the subprocess' `stdout` to a second Execa subprocess' `stdin`. This resolves with that second subprocess' [result](#subprocessresult). If either subprocess is rejected, this is rejected with that subprocess' [error](#subprocessresult) instead.367+[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the subprocess' `stdout` to a second Execa subprocess' `stdin`. This resolves with that second subprocess' [result](#subprocessresult). If either subprocess is rejected, this is rejected with that subprocess' [error](#execaerror) instead.368 369 This follows the same syntax as [`execa(file, arguments?, options?)`](#execafile-arguments-options) except both [regular options](#options-1) and [pipe-specific options](#pipeoptions) can be specified.370 371 This can be called multiple times to chain a series of subprocesses.61 unmodified lines433 Sends a [signal](https://nodejs.org/api/os.html#signal-constants) to the subprocess. The default signal is the [`killSignal`](#killsignal) option. `killSignal` defaults to `SIGTERM`, which [terminates](#isterminated) the subprocess.434 435 This returns `false` when the signal could not be sent, for example when the subprocess has already exited.436 430-When an error is passed as argument, its message and stack trace are kept in the [subprocess' error](#subprocessresult). The subprocess is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).437+When an error is passed as argument, it is set to the subprocess' [`error.cause`](#cause). The subprocess is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).438 439 [More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)440 441 ### SubprocessResult442 443 Type: `object`444 438-Result of a subprocess execution. On success this is a plain object. On failure this is also an `Error` instance.445+Result of a subprocess execution.446 440-The subprocess [fails](#failed) when:441-- its [exit code](#exitcode) is not `0`442-- it was [terminated](#isterminated) with a [signal](#signal)443-- [timing out](#timedout)444-- [being canceled](#iscanceled)445-- there's not enough memory or there are already too many subprocesses447+When the subprocess [fails](#failed), it is rejected with an [`ExecaError`](#execaerror) instead.448 449 #### command450 451 Type: `string`60 unmodified lines512 The output of the subprocess on [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1) and [other file descriptors](#stdio-1).513 514 Items are `undefined` when their corresponding [`stdio`](#stdio-1) option is set to [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). Items are arrays when their corresponding `stdio` option is a [transform in object mode](docs/transform.md#object-mode).515 514-#### message515-516-Type: `string`517-518-Error message when the subprocess failed to run. In addition to the [underlying error message](#originalMessage), it also contains some information related to why the subprocess errored.519-520-The subprocess [`stderr`](#stderr), [`stdout`](#stdout) and other [file descriptors' output](#stdio) are appended to the end, separated with newlines and not interleaved.521-522-#### shortMessage523-524-Type: `string`525-526-This is the same as the [`message` property](#message) except it does not include the subprocess [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio).527-528-#### originalMessage529-530-Type: `string | undefined`531-532-Original error message. This is the same as the `message` property excluding the subprocess [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio) and some additional information added by Execa.533-534-This is `undefined` unless the subprocess exited due to an `error` event or a timeout.535-516 #### failed517 518 Type: `boolean`519 46 unmodified lines566 If a signal terminated the subprocess, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.567 568 #### pipedFrom569 590-Type: [`SubprocessResult[]`](#subprocessresult)570+Type: [`Array<SubprocessResult | ExecaError>`](#subprocessresult)571 572 Results of the other subprocesses that were [piped](#pipe-multiple-subprocesses) into this subprocess. This is useful to inspect a series of subprocesses piped with each other.573 574 This array is initially empty and is populated each time the [`.pipe()`](#pipefile-arguments-options) method resolves.575 576+### ExecaError577+### ExecaSyncError578+579+Type: `Error`580+581+Exception thrown when the subprocess [fails](#failed), either:582+- its [exit code](#exitcode) is not `0`583+- it was [terminated](#isterminated) with a [signal](#signal), including [`.kill()`](#killerror)584+- [timing out](#timedout)585+- [being canceled](#iscanceled)586+- there's not enough memory or there are already too many subprocesses587+588+This has the same shape as [successful results](#subprocessresult), with the following additional properties.589+590+#### message591+592+Type: `string`593+594+Error message when the subprocess failed to run. In addition to the [underlying error message](#originalMessage), it also contains some information related to why the subprocess errored.595+596+The subprocess [`stderr`](#stderr), [`stdout`](#stdout) and other [file descriptors' output](#stdio) are appended to the end, separated with newlines and not interleaved.597+598+#### shortMessage599+600+Type: `string`601+602+This is the same as the [`message` property](#message) except it does not include the subprocess [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio).603+604+#### originalMessage605+606+Type: `string | undefined`607+608+Original error message. This is the same as the `message` property excluding the subprocess [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio) and some additional information added by Execa.609+610+This exists only if the subprocess exited due to an `error` event or a timeout.611+612+#### cause613+614+Type: `unknown | undefined`615+616+Underlying error, if there is one. For example, this is set by [`.kill(error)`](#killerror).617+618+This is usually an `Error` instance.619+620+#### code621+622+Type: `string | undefined`623+624+Node.js-specific [error code](https://nodejs.org/api/errors.html#errorcode), when available.625+626 ### options627 628 Type: `object`629 3 unmodified lines633 634 Type: `boolean`\635 Default: `true`636 607-Setting this to `false` resolves the promise with the error instead of rejecting it.637+Setting this to `false` resolves the promise with the [error](#execaerror) instead of rejecting it.638 639 #### shell640 641 Type: `boolean | string | URL`\460 unmodified lines