使用Stripe createPaymentMethod无法获取错误信息,求技术协助
Stripe createPaymentMethod 无错误返回问题排查与修复
核心问题
你的代码混合使用了await与.then()/.catch(),导致错误处理逻辑错位:
await会等待createPaymentMethod的Promise完成,但后续的.then()会生成新的Promise,外层await最终拿到的是console.log的返回值(undefined)- 原Promise的错误被
.catch()捕获后重新抛出,但如果外层没有对应的try/catch,这个错误会变成未处理的Promise拒绝,你无法在预期位置看到错误输出
修正后的代码方案
方案1:使用await + try/catch(推荐,逻辑更清晰)
try { const { paymentMethod, error } = await stripe.createPaymentMethod({ type: 'card', card: cardElement, billing_details: { name: fullName, email: email!, phone: mobile!, }, }); // 这里可以正常获取Stripe返回的error或paymentMethod console.log('支付方式信息:', paymentMethod); console.log('返回错误:', error); } catch (e) { // 捕获网络异常或Stripe服务端抛出的严重错误 console.error('创建支付方式异常:', e); }
方案2:使用纯链式调用(.then()/.catch())
stripe.createPaymentMethod({ type: 'card', card: cardElement, billing_details: { name: fullName, email: email!, phone: mobile!, }, }) .then(({ paymentMethod, error }) => { console.log('支付方式信息:', paymentMethod); console.log('返回错误:', error); }) .catch(e => { console.error('创建支付方式异常:', e); });
测试卡号验证说明
你使用的测试卡:
4000000000000002:会触发payment_method类型的错误4000000000000127:会触发card_declined类型的错误
修正代码后,应该能在error对象中看到包含code、message的详细错误信息。
内容的提问来源于stack exchange,提问作者ertemishakk
相关产品推荐
相关产品推荐

