Skip to content
Myr

clone.js

This file

Path

lib/return/clone.js

70 lines · 2.0 KiB · JavaScript

Last changed by

Split files (#837)ehmickybefore adoption672c2d7

History of this file

Take it

Split files (#837)ehmickybefore adoption672c2d7

lines 1–70why, one step back
1export const getFinalError = (initialError, message) => {
2 const error = createFinalError(initialError, message);3 previousErrors.add(error);4 return error;5};67const createFinalError = (error, message) => {8 if (!isErrorInstance(error)) {9 return new Error(message);10 }1112 return previousErrors.has(error)13 ? cloneError(error, message)14 : setErrorMessage(error, message);15};1617export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';1819const 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};2728const 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};3637// Known error properties38const COPIED_ERROR_PROPERTIES = [39 'cause',40 'errors',41 'code',42 'errno',43 'syscall',44 'path',45 'dest',46 'address',47 'port',48 'info',49];5051// 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/5171555const setErrorMessage = (error, newMessage) => {56 const {message, stack} = error;57 error.message = newMessage;58 error.stack = fixStack(stack, message, newMessage);59 return error;60};6162const fixStack = (stack, message, newMessage) => stack.includes(newMessage)63 ? stack64 : stack.replace(`: ${message}`, `: ${newMessage}`);6566// Two `execa()` calls might return the same error.67// So we must close those before directly mutating them.68export const isPreviousError = error => previousErrors.has(error);6970const previousErrors = new WeakSet();