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

私は単純なレスキューコールを試しましたが、レーキはそれを好みません。

エラーから救う方法は何ですか?

アップデート:

私のやり方

 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_endrescue例外を予期しています=>例外

レーキ0.9.2.2レール3.2.5

4

2 に答える 2

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
于 2012-06-06T23:56:12.453 に答える
3

私はまだコメントするのに十分な評判がありませんが、上記の答えの3番目のオプションに関して:例外から救出しないでください!

ExceptionはRubyの例外階層のルートであるため、、、、などのサブクラスを含むすべてから救助rescue Exceptionする場合。SyntaxErrorLoadErrorInterrupt

詳細を知りたい場合は、Rubyで `rescue Exception =>e`を実行するのが悪いスタイルである理由を確認してください。

于 2014-10-01T19:38:23.680 に答える