diff --git a/index.js b/index.js index ba6c662..9df3600 100644 --- a/index.js +++ b/index.js @@ -4,11 +4,26 @@ exports.fromCallback = function (fn) { return Object.defineProperty(function (...args) { if (typeof args[args.length - 1] === 'function') fn.apply(this, args) else { + // Capture stack trace of where the promise was created in case it rejects. + let caller_stack = new Error("Failing function was called from here").stack return new Promise((resolve, reject) => { fn.call( this, ...args, - (err, res) => (err != null) ? reject(err) : resolve(res) + (err, res) => { + if (err != null) { + if (err instanceof Error && typeof err.stack === 'string') { + // It is safe to improve the error's stack trace with + // information about where the Promise was created and where + // the err was passed from. + let e = new Error("Callback-based function called back with an error") + err.stack += "\n" + e.stack + "\n" + caller_stack + } + reject(err) + } else { + resolve(res) + } + } ) }) }