Search code examples
ruby-on-railsruby-on-rails-3rakeruby-on-rails-3.2

How to Rescue From An Error in Rake


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


Solution

  • 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