2014-06-25 26 views
3

在模型中使用方法時,是否可以呈現條紋錯誤消息作爲註釋。這是我目前處理模型中的條紋錯誤

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 

但是我不知道如何抓住這些錯誤,然後把它們放在通知內

任何幫助讚賞謝謝

+0

你想如何處理它?你想'save_with_payment'來表示驗證失敗嗎?另外,你有一個實例方法而不是一個類方法。 –

+0

對不起,我的方法混在一起,謝謝澄清。我想處理save_with_payment中的錯誤,並通過可能的通知通過通知向用戶顯示錯誤 – Richlewis

回答

5

你可以做到這一點,假設save_with_payment是

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 

你可能想看看是否有條紋它創建不過更具體的錯誤回調(before_create或before_save我會承擔),如果是的話,你可以添加對捐贈具有的特定屬性的錯誤。例如(彌補無效的電子郵件錯誤,因爲捐款有一個電子郵件的外觀)

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

另外,您可能希望通過付款拆分保存以調用其他兩種方法,一種方式爲客戶,另一種爲收費方式,以便您可以救援客戶在一個相關的錯誤和另一個相關的收費 –