1

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

Mab879
  • 608
  • 16
  • 33

2 Answers2

4

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
Mori
  • 27,279
  • 10
  • 68
  • 73
3

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?

Community
  • 1
  • 1
maxhm10
  • 1,034
  • 9
  • 20