2016-11-30 15 views
0

ブロックでレスキューを行う正しい方法ですか?レスキューブロックを行う最良の方法

また、それは最短ですか?

def rescue_definition 
    begin 
     user.begin_rescue 
    rescue Example::ParameterValidationError => e 
     redirect_to :back, error: e.message_to_purchaser 
    rescue Example::ProcessingError => e 
     redirect_to :back, error: e.message_to_purchaser 
    rescue Example::Error 
     redirect_to :back, error: e.message_to_purchaser 
    else 
     if user 
      flash['success'] = 'OK' 
     else 
      flash['error'] = 'NO' 
     end 
    end 
    redirect_to :back 
end 

答えて

1

始める使用するアイデア、救助、確実にbeginブロックでエラーを発生させることができるよりも、あなたはより多くのrescueブロックO 1でエラーを処理することができ、最終的には、オプションを置くことができる方法を置くことですensureリリースリソースなどの成功シナリオまたは失敗シナリオの両方で実行したい文のブロック。

すべてのメソッドをbegin、rescue、ブロックが確実に処理されるようにするには、beginキーワードはオプションです。キーワードを使用するかどうかは、最短オプションを求めているので、マイナーあなたのコードを変更:

def rescue_definition 
    user.begin_rescue 
    # and any other stuff you want to execute 
    if user 
    flash['success'] = 'OK' 
    else 
    flash['error'] = 'NO' 
    end 
    redirect_to :back 
rescue Example::ParameterValidationError => e 
    redirect_to :back, error: e.message_to_purchaser 
rescue Example::ProcessingError => e 
    redirect_to :back, error: e.message_to_purchaser 
rescue Example::Error 
    redirect_to :back, error: e.message_to_purchaser 
end 

あなたはそれがさらに短くしたい場合は、1つのレスキューブロックで複数の例外タイプを救うことができます。

def rescue_definition 
    user.begin_rescue 
    # and any other stuff you want to execute 
    if user 
    flash['success'] = 'OK' 
    else 
    flash['error'] = 'NO' 
    end 
    redirect_to :back 
rescue Example::ParameterValidationError, Example::ProcessingError, Example::Error => e 
    redirect_to :back, error: e.message_to_purchaser 
end 
+0

お返事ありがとうございます。私はあなたの提案に従います。また、私は3回のレスキューで 'redirect_to:back、error:e.message_to_purchaser'を繰り返しています。それを行う最短の方法はありますか? – Bengala

+0

@Bengalaこれが正解であれば、それを受け入れるべきです。 – mysmallidea

+0

私は "redirect_to:back、error:e.message_to_purchaser"を3回繰り返しているので正解ではありません。私はそれがもっと短くてもいいと確信しています。 – Bengala

0

Aguarのポストは、現在の実装を処理します。同じ方法ですべてのエラーを処理する場合、それらをカスタムクラスから継承させて、1つのレスキューコールですべてのエラーをキャッチすることができます。

def stuff 
    user.stuff 
    if user 
    flash['success'] = 'Ya' 
    else 
    flash['error'] = 'Nah' 
    end 
    redirect_to .... 
rescue CustomClassError => e 
    redirect_to :back, error: e.message_to_purchaser 
rescue NonCustomErrors => e 
    #handle it 
end 
関連する問題