Skip to content

Instantly share code, notes, and snippets.

@snehesht
Created March 3, 2022 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snehesht/7658c7cb5185c63d2643560e82eff971 to your computer and use it in GitHub Desktop.
Save snehesht/7658c7cb5185c63d2643560e82eff971 to your computer and use it in GitHub Desktop.
Clarify Error Stacks
function splitStack(err: Error | string): Array<string> {
if (typeof err === 'string') return [`Error: ${err}`];
else if (err.stack) return err.stack.split('\n');
else return [`${err.name}: ${err.message}`];
}
export = function clarify(innerError: Error | string, message: string): Error {
const outerError = new Error(message);
const outerStack = outerError.stack!.split('\n');
outerStack.splice(1, 1);
const innerStack = splitStack(innerError);
innerStack[0] = ' ' + innerStack[0];
for (let i = 1; i < outerStack.length; i++) {
if (innerStack.includes(outerStack[i])) {
outerStack.splice(i);
break;
}
}
outerError.stack = outerStack.concat(innerStack).join('\n');
return outerError;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment