Skip to content

Instantly share code, notes, and snippets.

@joeytwiddle
Last active February 7, 2019 15:10
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeytwiddle/8c357b8a4ac6803a0f188d495901b6bc to your computer and use it in GitHub Desktop.
Save joeytwiddle/8c357b8a4ac6803a0f188d495901b6bc to your computer and use it in GitHub Desktop.
'use strict';
const theGlobal = typeof window === 'object' ? window : global;
const realPromiseConstructor = theGlobal.Promise;
const wrappedPromiseConstructor = function (resolve, reject, progress) {
const originalPromiseInstance = new realPromiseConstructor(resolve, reject, progress);
// Who called us? Let's store it.
const stackWhenCalled = new Error().stack;
const wrappedPromiseInstance = originalPromiseInstance.catch((err) => {
try {
err.stack = err.stack || '';
err.stack += '\nDuring promise started:\n' + stackWhenCalled.split('\n').slice(3).join('\n');
} catch (err2) {
console.error("promiseDebugging.reportLongStackTraces had difficulty adding to the stack:", err2);
}
return realPromiseConstructor.reject(err);
});
return wrappedPromiseInstance;
};
Object.setPrototypeOf(wrappedPromiseConstructor, realPromiseConstructor);
theGlobal.Promise = wrappedPromiseConstructor;
@joeytwiddle
Copy link
Author

joeytwiddle commented Jun 2, 2017

I find this pretty useful, but NodeJS developers might find the longjohn module even more useful, because it can track long stacktraces through callbacks as well as through promises. As a result, it also works when your app and its dependencies are using different promise libraries.

I sometimes add clarify too (and tweak it a little) to remove some of the uninteresting lines from the stacktrace.

Update: This package trace-and-clarify-if-possible looks promising

@houshuang
Copy link

This one just saved my life!

@joeytwiddle
Copy link
Author

joeytwiddle commented Dec 6, 2018

Unfortunately, this trick does not work with native async-await, because the engine doesn't call our global promise constructor.

But it does work with transpiled async-await.

NodeJS now does this out of the box, since --async-stack-traces has been enabled by default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment