gpt4 book ai didi

ruby-on-rails - 处理模型中的 Stripe 错误

转载 作者:数据小太阳 更新时间:2023-10-29 07:52:41 24 4
gpt4 key购买 nike

在模型中使用方法时,是否可以将 Stripe 错误消息呈现为通知。这是我现在的 Controller

def create
@donation = @campaign.donations.create(donation_params)
if @donation.save_with_payment
redirect_to @campaign, notice: 'Card charged successfully.'
else
render :new
end
end

我的方法是这样的

def save_with_payment
customer = Stripe::Customer.create(
:email => email,
:card => stripe_token
)

charge = Stripe::Charge.create(
:customer => customer.id,
:amount => donation_amount,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
end

我从其他人的例子中注意到 Stripe 有一个

rescue Stripe::error
rescue Stripe::InvalidRequestError => e

但我不确定如何获取这些错误,然后将它们放入通知中。

最佳答案

你可以这样做,假设 save_with_payment 是一个回调(我假设是 before_create 或 before_save)

def save_with_payment
customer = Stripe::Customer.create(
:email => email,
:card => stripe_token
)

charge = Stripe::Charge.create(
:customer => customer.id,
:amount => donation_amount,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
rescue Stripe::error => e
errors[:base] << "This donation is invalid because #{e}"
rescue Stripe::InvalidRequestError => e
errors[:base] << "This donation is invalid because #{e}"
end

你可能想看看 stripe 是否有它创建的更具体的错误,如果有的话,你可以将错误添加到捐赠具有的特定属性上。例如(编造一个无效的电子邮件错误,因为捐赠看起来有一封电子邮件)

rescue Stripe::InvalidEmailError => e
errors.add(:email, e)
end

关于ruby-on-rails - 处理模型中的 Stripe 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24411271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com