Reputation: 608
How do I rescue from a
undefined method
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
I have tried a plain rescue call, but rake isn't liking it.
What is way to rescue from the error?
UPDATE:
The way I was doing it
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
The Error /home/user/rails_projects/assignitapp/lib/tasks/daily.rake:25: syntax error, unexpected keyword_rescue, expecting keyword_end rescue Exception => exception
Rake 0.9.2.2 Rails 3.2.5
Upvotes: 1
Views: 4033
Reputation: 27789
Use try
to wrap the problem method and return nil if it doesn't exist. E.g.:
unless @customer = Stripe::Customer.try(:retrieve, user.stripe_customer_token)
# Logic
end
Alternatively, this catches more errors:
unless @customer = Stripe::Customer.retrieve(user.stripe_customer_token) rescue nil
# Logic
end
Or this is more what you were trying for:
@users.each do |user|
begin
@customer = Stripe::Customer.retrieve(user.stripe_customer_token)
rescue StandardError => error
# handle error
end
end
Upvotes: 4
Reputation: 1042
I still haven't enough reputation to comment, but regarding the above answer's third option: Don't rescue from Exception!
Exception
is the root of Ruby's exception hierarchy, so when you rescue Exception
you rescue from everything, including subclasses such as SyntaxError
, LoadError
, and Interrupt
.
If you want to learn more, check out Why is it a bad style to `rescue Exception => e` in Ruby?
Upvotes: 3