Missing stack trace on errors
Consider the following code snippet:
const customerData = {}; // some customer data
try {
await stripe.customers.create(customerData);
} catch (err) {
console.error(err);
}
When the api call fails due to any kind of error, the promise is rejected so an error is thrown and the catch block is triggered.
This is an example of error thrown by the stripe-node module:
Error: No such PaymentMethod: 'pm_card_vaaaaasa'
at Function.generate (C:\Users\Alessandro\Documents\Projects\clickout\billing\node_modules\stripe\lib\Error.js:39:16)
at IncomingMessage.<anonymous> (C:\Users\Alessandro\Documents\Projects\clickout\billing\node_modules\stripe\lib\StripeResource.js:190:33)
at Object.onceWrapper (events.js:299:28)
at IncomingMessage.emit (events.js:215:7)
at endReadableNT (_stream_readable.js:1184:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
As you can see, the original stack trace is lost and there is no reference to the file and line of code that threw the error, making debug very difficult.
For reference, this is the stack trace of a standard javascript Error, thrown on purpose (for this bug report) from the same file, just a line before the create customer call.
error: Error: this is a standard error stack track
at CustomerService._createCustomer (C:\Users\Alessandro\Documents\Projects\clickout\billing\app\services\customer.service.js:147:13)
at C:\Users\Alessandro\Documents\Projects\clickout\billing\app\services\customer.service.js:50:25
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async LockService.withLock (C:\Users\Alessandro\Documents\Projects\clickout\billing\app\services\lock.service.js:16:22)
at async CustomerService.create (C:\Users\Alessandro\Documents\Projects\clickout\billing\app\services\customer.service.js:21:22)
at async handler (C:\Users\Alessandro\Documents\Projects\clickout\billing\app\api\v1\controllers\customer.controller.js:35:24)`
If you take a look at it, the stack trace contains a clear reference to the function, file and line that caused the error, along with upper level function calls.
node: 12.13.1 stripe-node: 8.121.0
Hey @AleG94 -- thanks for the example and sample output. I'm looking into this to see what's possible today and what might be doable in future.
The core of what's going on here is that what you're seeing is the call stack. With the async execution, that stack is what is present when the error is raised -- the work is scheduled separate from you made the call in the event loop. See this Stack Overflow answer for an example and other info.
That said, it is possible to have longer call stacks bridging async/await patterns to the visibility you're expecting, which is supported start in Node 12 / V8 7.3. See an example of this here, it's quite nice:
Error: Oops
at baz (/workspace/test.js:20:9)
at async bar (/workspace/test.js:15:3)
at async foo (/workspace/test.js:10:3)
at async run (/workspace/test.js:5:3)
As far as I can tell, this requires the use of async functions, and currently does not work with stripe-node. I'm logging this as a feature request so the team can investigate whether we can make changes to support this, but I'm not able to commit to it or offer any timeline.
Instead, I'd suggest a couple of workarounds:
- When you catch the API response error, you can
throwyour own new error which will put it's own location in the stack. - While not recommended in production, you can use a tool like
tracefor debugging when encountering an error. (Docs here) Briefly, in my repro script shaped like your example:
node --stack_trace_limit=100 -r trace node-issue-1066-repro-call-stack.js
Produces:
Error: You cannot supply a test PaymentMethod ID as the `source` parameter. Please use the `payment_method` parameter instead. If you wish to set a default payment method for this Customer for future Invoices, [retrieve the PaymentMethod](/docs/api/payment_methods/retrieve) using the test ID and then set [invoice_settings.default_payment_method](/docs/api/customers/update#update_customer-invoice_settings-default_payment_method).
at Function.generate (/Users/brendanm/support/snippets/node_modules/stripe/lib/Error.js:40:16)
at IncomingMessage.<anonymous> (/Users/brendanm/support/snippets/node_modules/stripe/lib/StripeResource.js:190:39)
at Object.onceWrapper (events.js:421:28)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1220:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
****at runAsync (/Users/brendanm/support/snippets/scripts-node/node-issue-1066-repro-call-stack.js:20:35)****
at new Promise (<anonymous>)
... (more lines, not relevant)
The highlighted line is where I called await stripe.customers.create(...).
Hope that helps, and I hope to be able to follow up here in future about supporting the longer stack trace.
Hey @brendanm-stripe, thanks for the feedback and supportive explanation.
I will probably go for workaround n° 1 and throw my own custom error, which is more suited for production environment.
Great, glad that's workable @AleG94 !
Closing this, but can update here if we can eventually support the extended async traces.
For anyone curious about a more generic fix, here's the code for a Stripe wrapper which gives more helpful stack traces:
const orgStripe = new Stripe(process.env.STRIPE_SECRET_KEY, {apiVersion: "2020-08-27"});
const wrapper: ProxyHandler<any> = {
get(target, key) {
const val = target[key];
if (typeof val === "object" && val !== null) {
return new Proxy(val, wrapper);
} else {
if (typeof val === "function") {
const stackHolder = {} as any;
Error.captureStackTrace(stackHolder);
return (...args: any[]) => {
const result = val.call(target, ...args);
if (result && typeof result.then === "function") {
return result.catch((err: any) => {
err.stack = stackHolder.stack || err.stack;
return Promise.reject(err);
});
} else {
return result;
}
};
} else {
return val;
}
}
},
};
const wrappedStripe = new Proxy(orgStripe, wrapper) as Stripe;
the magic happens at
const stackHolder = {} as any;
Error.captureStackTrace(stackHolder);
and
return result.catch((err: any) => {
err.stack = stackHolder.stack || err.stack;
return Promise.reject(err);
});
Maybe something to consider for the underlying implementation to avoid having to use this wrapper.
Word of warning to others who come across this issue, the wrapping proxy will not work with await for syntax, nor will it work for the autoPagingEach methods for the stripe resources.
If I'm understanding right, this'll also incur the CPU cost/overhead of generating a stack trace on every Stripe client dereference/API call, not just on errors? That might add a lot of non-trivial cost for applications at scale…
FYI - We shipped a fix for this in v22.1.0 of the node SDK! It's still two stack traces, but it should lead back to a path in your code which should help debugging a lot.
Thanks for bearing with us!
Example:
Error: Invalid API Key provided: sk_test_fake
at generateV1Error (/Users/xavdid/stripe/hello-sdks/node/node_modules/stripe/src/Error.ts:27:12)
at <anonymous> (/Users/xavdid/stripe/hello-sdks/node/node_modules/stripe/src/RequestSender.ts:194:23)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
Originating from:
at CustomerResource._makeRequest (/Users/xavdid/stripe/hello-sdks/node/node_modules/stripe/src/StripeResource.ts:97:27)
at CustomerResource.list (/Users/xavdid/stripe/hello-sdks/node/node_modules/stripe/src/resources/Customers.ts:207:17)
at listCustomers (/Users/xavdid/stripe/hello-sdks/node/index.ts:9:52)
at <anonymous> (/Users/xavdid/stripe/hello-sdks/node/index.ts:20:7)
at ModuleJob.run (node:internal/modules/esm/module_job:430:25)
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:661:26)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5)