2012-06-06 41 views
1

如何從一個如何從錯誤中搶救耙

未定義的方法

error in this code 

for user in @users do 
    @customer = Stripe::Customer.retrieve(user.stripe_customer_token) 
     if @customer.subscription.nil? 
     elsif @customer.subscription.plan.id == 2 
      user.silver_reset 
     elsif @customer.subscription.plan.id == 3 
      user.gold_reset 
     end 
    end 

我已經嘗試了簡單的救援電話搶救,但耙不喜歡它。

從錯誤中拯救的方法是什麼?

UPDATE:

我是這樣做

for user in @users do 
      @customer = Stripe::Customer.retrieve(user.stripe_customer_token) 
     rescue_from Exception => exception 
      # Logic 
     end 
     if @customer.subscription.nil? 
     elsif @customer.subscription.plan.id == 2 
      user.silver_reset 
     elsif @customer.subscription.plan.id == 3 
      user.gold_reset 
     end 
    end 

的錯誤 /home/user/rails_projects/assignitapp/lib/tasks/daily.rake:25方式:語法錯誤,意想不到的keyword_rescue ,期望keyword_end 救援異常=>異常

瑞克0.9.2.2 滑軌3.2.5

+0

你如何試圖拯救? –

+0

「Rake不喜歡它」 - 您嘗試的代碼是什麼以及您獲得了哪些錯誤或行爲? –

+0

添加了Henrique和Jordon要求提供的信息。 – Mab879

回答

4

使用try來包裝問題方法,如果不存在,則返回nil。例如:

unless @customer = Stripe::Customer.try(:retrieve, user.stripe_customer_token) 
    # Logic 
end 

或者,這捕獲更多的錯誤:

unless @customer = Stripe::Customer.retrieve(user.stripe_customer_token) rescue nil 
    # Logic 
end 

或者這更是你所想的:

@users.each do |user| 
    begin 
    @customer = Stripe::Customer.retrieve(user.stripe_customer_token) 
    rescue StandardError => error 
    # handle error 
    end 
end 
+0

第三個選項應該適用於我。 – Mab879

1

我還沒有足夠的信譽發表評論,但關於上述答案的第三個選項:不要從異常中拯救!

Exception是Ruby的異常層次的根,所以當你rescue Exception一切,包括子類,如SyntaxErrorLoadErrorInterrupt搶救。

如果您想了解更多,請Why is it a bad style to `rescue Exception => e` in Ruby?