处理模型中的条带错误

时间:2014-06-25 14:22:44

标签: ruby-on-rails ruby ruby-on-rails-4 stripe-payments

在模型中使用方法时,是否可以将条带错误消息呈现为anotices。这是我的控制者

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

我注意到其他人的exmaples条纹有一个

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

但我不知道如何抓住这些错误,然后将它们放在通知中

任何帮助表示感谢

1 个答案:

答案 0 :(得分:5)

你可以这样做,假设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

您可能希望查看条带是否包含其创建的更多特定错误,如果是这样,您可以将错误添加到捐赠所具有的特定属性中。例如(编写无效的电子邮件错误,因为捐赠的外观是电子邮件)

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