条纹-PaymentIntents handleCardPayment()-如何捕获JS错误?

时间:2019-04-01 12:33:24

标签: javascript stripe-payments

我已经根据Stripe提供的示例编写了代码:

namebucket

https://stripe.com/docs/stripe-js/reference#stripe-handle-card-payment

例如,我遇到的问题是我没有为var cardButton = document.getElementById('card-button'); var clientSecret = cardButton.dataset.secret; cardButton.addEventListener('click', function(ev) { stripe.handleCardPayment( clientSecret, cardElement ).then(function(result) { if (result.error) { // Display error.message in your UI. } else { // The payment has succeeded. Display a success message. } }); }); 提供值。提交表单时,我在控制台中收到此错误:

enter image description here

如何捕获此错误(和其他JS错误)并在UI中显示该错误?我尝试在clientSecret函数中捕获它,但我认为这仅是为了报告API响应中的错误。

2 个答案:

答案 0 :(得分:0)

继续阅读Promises。如果 stripe.handleCardPayment 成功处理,它将返回返回值作为第一个参数。如果不是,它将被拒绝并在第二个参数中发送。您必须这样处理:

var cardButton = document.getElementById('card-button');
var clientSecret = cardButton.dataset.secret;

cardButton.addEventListener('click', function(ev) {
stripe.handleCardPayment(
clientSecret, cardElement
).then(function(result) {
if (result.error) {
  // Display error.message in your UI.
} else {
  // The payment has succeeded. Display a success message.
}
},
function(err){
console.log('err:', err); // Handle your error here.
});
});

答案 1 :(得分:0)

好的,我知道了。只需一个简单的try / catch

try {
  stripe.handleCardPayment(
    clientSecret, cardElement
  ).then(function(result) {
    if (result.error) {
      // Display error.message in your UI.
    } else {
      // The payment has succeeded. Display a success message.
    }
  });
}
catch(error) {
  console.log(error.message);
}