处理模型中的条带错误

Ric*_*wis 3 ruby ruby-on-rails stripe-payments ruby-on-rails-4

在模型中使用方法时,是否可以将条带错误消息呈现为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
Run Code Online (Sandbox Code Playgroud)

我的方法是这样的

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
Run Code Online (Sandbox Code Playgroud)

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

rescue Stripe::error
 rescue Stripe::InvalidRequestError => e
Run Code Online (Sandbox Code Playgroud)

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

任何帮助表示感谢

j-d*_*exx 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
Run Code Online (Sandbox Code Playgroud)

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

rescue Stripe::InvalidEmailError => e
  errors.add(:email, e)
end
Run Code Online (Sandbox Code Playgroud)