Last active
February 7, 2019 15:10
-
-
Save joeytwiddle/8c357b8a4ac6803a0f188d495901b6bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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; |
This one just saved my life!
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
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