Fix `error.stack` with `stream.destroy(error)` (#814)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 9cbb817 · Browse files · 6 files·+270 added−146 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+270 added−146 removed
- tests:+142 added−83 removed
- other:+128 added−63 removed
Provenance
- Commit
07a9890- Tree
2311b00- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
9cbb817
6 files changed+270 added−146 removed
added:lib/clone.js+70 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970export const getFinalError = (initialError, message) => { const error = createFinalError(initialError, message); previousErrors.add(error); return error;};
const createFinalError = (error, message) => { if (!isErrorInstance(error)) { return new Error(message); }
return previousErrors.has(error) ? cloneError(error, message) : setErrorMessage(error, message);};
export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';
const cloneError = (oldError, newMessage) => { const {name, message, stack} = oldError; const error = new Error(newMessage); error.stack = fixStack(name, stack, message, newMessage); Object.defineProperty(error, 'name', {value: name, enumerable: false, configurable: true, writable: true}); copyErrorProperties(error, oldError); return error;};
const copyErrorProperties = (newError, previousError) => { for (const propertyName of COPIED_ERROR_PROPERTIES) { const descriptor = Object.getOwnPropertyDescriptor(previousError, propertyName); if (descriptor !== undefined) { Object.defineProperty(newError, propertyName, descriptor); } }};
// Known error propertiesconst COPIED_ERROR_PROPERTIES = [ 'cause', 'errors', 'code', 'errno', 'syscall', 'path', 'dest', 'address', 'port', 'info',];
// Sets `error.message`.// Fixes `error.stack` not being updated when it has been already accessed, since it is memoized by V8.// For example, this happens when calling `stream.destroy(error)`.// See https://github.com/nodejs/node/issues/51715const setErrorMessage = (error, newMessage) => { const {name, message, stack} = error; error.message = newMessage; error.stack = fixStack(name, stack, message, newMessage); return error;};
const fixStack = (name, stack, message, newMessage) => stack.includes(newMessage) ? stack : stack.replace(`${name}: ${message}`, `${name}: ${newMessage}`);
// Two `execa()` calls might return the same error.// So we must close those before directly mutating them.export const isPreviousError = error => previousErrors.has(error);
const previousErrors = new WeakSet();modified:lib/error.js+55 added-62 removed
12345678910111213141516171819202122232425262728293031323334353616 unmodified lines53545556305758325960613536373862636465414243444546474849666768698 unmodified lines78798081828384858687888990919293944 unmodified lines99100101102781031048081828384858687881051061071081091101111121131141151161171181199091929394959697989910010112012112212321 unmodified lines145146147148131132133134135136137138139140141142143144145146147148149150151152153154155import {signalsByName} from 'human-signals';import stripFinalNewline from 'strip-final-newline';import {isBinary, binaryToString} from './stdio/utils.js';import {fixCwdError} from './cwd.js';import {getFinalError, isPreviousError} from './clone.js';
const createMessages = ({ stdio, all, error, signal, signalDescription, exitCode, command, timedOut, isCanceled, timeout, cwd,}) => { const errorCode = error?.code; const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); const originalMessage = getOriginalMessage(error, cwd); const newline = originalMessage === '' ? '' : '\n'; const shortMessage = `${prefix}: ${command}${newline}${originalMessage}`; const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all]; const message = [shortMessage, ...messageStdio, ...stdio.slice(3)] .map(messagePart => stripFinalNewline(serializeMessagePart(messagePart))) .filter(Boolean) .join('\n\n'); return {originalMessage, shortMessage, message};};
export const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { if (timedOut) { return `Command timed out after ${timeout} milliseconds`; }16 unmodified lines
return 'Command failed';};
const getErrorSuffix = (error, cwd) => {const getOriginalMessage = (error, cwd) => { if (error === undefined) { return {originalMessage: '', suffix: ''}; return ''; }
const originalErrorMessage = previousErrors.has(error) ? error.originalMessage : String(error?.message ?? error); const originalMessage = fixCwdError(originalErrorMessage, cwd); const suffix = `\n${originalMessage}`; return {originalMessage, suffix}; const originalErrorMessage = isPreviousError(error) ? error.originalMessage : String(error?.message ?? error); return fixCwdError(originalErrorMessage, cwd);};
// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.// We normalize them to `undefined`export const normalizeExitPayload = (rawExitCode, rawSignal) => { const exitCode = rawExitCode === null ? undefined : rawExitCode; const signal = rawSignal === null ? undefined : rawSignal; const signalDescription = signal === undefined ? undefined : signalsByName[rawSignal].description; return {exitCode, signal, signalDescription};};
const serializeMessagePart = messagePart => Array.isArray(messagePart) ? messagePart.map(messageItem => serializeMessageItem(messageItem)).join('') : serializeMessageItem(messagePart);
8 unmodified lines
return '';};
// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.// We normalize them to `undefined`export const normalizeExitPayload = (rawExitCode, rawSignal) => { const exitCode = rawExitCode === null ? undefined : rawExitCode; const signal = rawSignal === null ? undefined : rawSignal; const signalDescription = signal === undefined ? undefined : signalsByName[rawSignal].description; return {exitCode, signal, signalDescription};};
export const makeError = ({ stdio, all, error: rawError,4 unmodified lines timedOut, isCanceled, options: {timeoutDuration, timeout = timeoutDuration, cwd},}) => { let error = rawError?.discarded ? undefined : rawError; const initialError = rawError?.discarded ? undefined : rawError; const {exitCode, signal, signalDescription} = normalizeExitPayload(rawExitCode, rawSignal); const errorCode = error?.code; const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); const {originalMessage, suffix} = getErrorSuffix(error, cwd); const shortMessage = `${prefix}: ${command}${suffix}`; const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all]; const message = [shortMessage, ...messageStdio, ...stdio.slice(3)] .map(messagePart => stripFinalNewline(serializeMessagePart(messagePart))) .filter(Boolean) .join('\n\n'); const {originalMessage, shortMessage, message} = createMessages({ stdio, all, error: initialError, signal, signalDescription, exitCode, command, timedOut, isCanceled, timeout, cwd, }); const error = getFinalError(initialError, message);
if (!isErrorInstance(error)) { error = new Error(message); } else if (previousErrors.has(error)) { const newError = new Error(message); copyErrorProperties(newError, error); error = newError; } else { error.message = message; }
previousErrors.add(error);
error.shortMessage = shortMessage; error.originalMessage = originalMessage; error.command = command; error.escapedCommand = escapedCommand;21 unmodified lines }
return error;};
export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';
const copyErrorProperties = (newError, previousError) => { for (const propertyName of COPIED_ERROR_PROPERTIES) { const descriptor = Object.getOwnPropertyDescriptor(previousError, propertyName); if (descriptor !== undefined) { Object.defineProperty(newError, propertyName, descriptor); } }};
// Known Node.js-specific error propertiesconst COPIED_ERROR_PROPERTIES = [ 'code', 'errno', 'syscall', 'path', 'dest', 'address', 'port', 'info',];
const previousErrors = new WeakSet();modified:lib/kill.js+2 added-1 removed
1 import {addAbortListener} from 'node:events';2 import os from 'node:os';3 import {setTimeout} from 'node:timers/promises';4 import {onExit} from 'signal-exit';5-import {normalizeExitPayload, getErrorPrefix, isErrorInstance} from './error.js';5+import {normalizeExitPayload, getErrorPrefix} from './error.js';6+import {isErrorInstance} from './clone.js';7 8 const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;9 10 // Monkey-patches `childProcess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`109 unmodified linesadded:test/clone.js+142 added
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 childProcess = execa('empty.js');10+ childProcess.emit('error', error);11+ const {originalMessage, shortMessage, message} = await t.throwsAsync(childProcess);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 childProcess = execa('empty.js');31+ childProcess.emit('error', {message: foobarString});32+ await t.throwsAsync(childProcess, {message: new RegExp(foobarString)});33+});34+35+const runAndFail = (t, fixtureName, argument, error) => {36+ const childProcess = execa(fixtureName, [argument]);37+ childProcess.emit('error', error);38+ return t.throwsAsync(childProcess);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 childProcess = execa('empty.js');120+ childProcess.emit('error', error);121+ t.is(await t.throwsAsync(childProcess), error);122+ t.is(error.message, `Command failed: empty.js\n${message}`);123+ t.true(error.stack.startsWith(`Error: Command failed: empty.js\n${message}`));124+});125+126+test('Cloned errors keep the stack trace', async t => {127+ const message = 'test';128+ const error = new Error(message);129+ const stack = error.stack.split('\n').filter(line => line.trim().startsWith('at ')).join('\n');130+131+ const childProcess = execa('empty.js');132+ childProcess.emit('error', error);133+ t.is(await t.throwsAsync(childProcess), error);134+135+ const secondChildProcess = execa('empty.js');136+ secondChildProcess.emit('error', error);137+ const secondError = await t.throwsAsync(secondChildProcess);138+ t.not(secondError, error);139+ t.is(secondError.message, `Command failed: empty.js\n${message}`);140+ t.is(secondError.stack, `Error: Command failed: empty.js\n${message}\n${stack}`);141+});142+modified:test/error.js-83 removed
2 unmodified lines3 import {execa, execaSync} from '../index.js';4 import {setFixtureDir} from './helpers/fixtures-dir.js';5 import {fullStdio, getStdio} from './helpers/stdio.js';6 import {noopGenerator, outputObjectGenerator} from './helpers/generator.js';7-import {foobarString} from './helpers/input.js';7 8 const isWindows = process.platform === 'win32';9 10 setFixtureDir();316 unmodified lines327 test('error.code is defined on failure if applicable', async t => {328 const {code} = await t.throwsAsync(execa('noop.js', {uid: true}));329 t.is(code, 'ERR_INVALID_ARG_TYPE');330 });332-333-const testUnusualError = async (t, error) => {334- const childProcess = execa('empty.js');335- childProcess.emit('error', error);336- const {originalMessage, shortMessage, message} = await t.throwsAsync(childProcess);337- t.is(originalMessage, String(error));338- t.true(shortMessage.includes(String(error)));339- t.is(message, shortMessage);340-};341-342-test('error instance can be null', testUnusualError, null);343-test('error instance can be false', testUnusualError, false);344-test('error instance can be a string', testUnusualError, 'test');345-test('error instance can be a number', testUnusualError, 0);346-test('error instance can be a BigInt', testUnusualError, 0n);347-test('error instance can be a symbol', testUnusualError, Symbol('test'));348-test('error instance can be a function', testUnusualError, () => {});349-test('error instance can be an array', testUnusualError, ['test', 'test']);350-351-test('error instance can be undefined', async t => {352- const childProcess = execa('empty.js');353- childProcess.emit('error');354- const {originalMessage, shortMessage, message} = await t.throwsAsync(childProcess);355- t.is(originalMessage, '');356- t.is(shortMessage, 'Command failed: empty.js');357- t.is(message, shortMessage);358-});359-360-test('error instance can be a plain object', async t => {361- const childProcess = execa('empty.js');362- childProcess.emit('error', {message: foobarString});363- await t.throwsAsync(childProcess, {message: new RegExp(foobarString)});364-});365-366-const runAndFail = (t, fixtureName, argument, error) => {367- const childProcess = execa(fixtureName, [argument]);368- childProcess.emit('error', error);369- return t.throwsAsync(childProcess);370-};371-372-const testErrorCopy = async (t, getPreviousArgument) => {373- const fixtureName = 'empty.js';374- const argument = 'two';375-376- const previousArgument = await getPreviousArgument(t, fixtureName);377- const previousError = await runAndFail(t, fixtureName, 'foo', previousArgument);378- const error = await runAndFail(t, fixtureName, argument, previousError);379- const message = `Command failed: ${fixtureName} ${argument}\n${foobarString}`;380-381- t.not(error, previousError);382- t.is(error.command, `${fixtureName} ${argument}`);383- t.is(error.message, message);384- t.true(error.stack.includes(message));385- t.is(error.shortMessage, message);386- t.is(error.originalMessage, foobarString);387-};388-389-test('error instance can be shared', testErrorCopy, () => new Error(foobarString));390-test('error string can be shared', testErrorCopy, () => foobarString);391-test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));392-393-const testErrorCopyProperty = async (t, propertyName, isCopied) => {394- const propertyValue = 'test';395- const initialError = new Error(foobarString);396- initialError[propertyName] = propertyValue;397-398- const previousError = await runAndFail(t, 'empty.js', 'foo', initialError);399- t.is(previousError, initialError);400-401- const error = await runAndFail(t, 'empty.js', 'bar', previousError);402- t.is(error[propertyName] === propertyValue, isCopied);403-};404-405-test('error.code can be copied', testErrorCopyProperty, 'code', true);406-test('error.errno can be copied', testErrorCopyProperty, 'errno', true);407-test('error.syscall can be copied', testErrorCopyProperty, 'syscall', true);408-test('error.path can be copied', testErrorCopyProperty, 'path', true);409-test('error.dest can be copied', testErrorCopyProperty, 'dest', true);410-test('error.address can be copied', testErrorCopyProperty, 'address', true);411-test('error.port can be copied', testErrorCopyProperty, 'port', true);412-test('error.info can be copied', testErrorCopyProperty, 'info', true);413-test('error.other cannot be copied', testErrorCopyProperty, 'other', false);modified:package.json+1 added
78 unmodified lines79 ]80 },81 "ava": {82 "workerThreads": false,83+ "concurrency": 1,84 "timeout": "60s"85 },86 "xo": {87 "rules": {5 unmodified lines