2016-09-28 7 views
1
class MyKlass 

    include ActiveSupport::Rescuable 

    rescue_from Exception do 
    return "rescued" 
    end 

    #other stuff 
end 

MyKlassは純粋なルビーオブジェクトですが、Railsアプリケーション内で定義されています。レスキュー可能なモジュールが含まれていないのはなぜですか?

railsコンソールでMyKlassインスタンスを呼び出して、それに確実に例外を発生させるメソッドに適用しようとすると、レスキューされる予定のエラー以外は何も起こりません。ここで

答えて

1

は、それがどのように使用するかである:それはExceptionを救出することは犯罪であること、言うまでもない

class MyKlass 
    include ActiveSupport::Rescuable 
    # define a method, which will do something for you, when exception is caught 
    rescue_from Exception, with: :my_rescue 

    def some_method(&block) 
    yield 
    rescue Exception => exception 
    rescue_with_handler(exception) || raise 
    end 

    # do whatever you want with exception, for example, write it to logs 
    def my_rescue(exception) 
    puts "Exception catched! #{exception.class}: #{exception.message}" 
    end 
end 

MyKlass.new.some_method { 0/0 } 
# Exception catched! ZeroDivisionError: divided by 0 
#=> true 

+0

私はrescue_fromのポイントは、私は各メソッドにレスキューを含める必要はないということです。私はそのうちの20個を持っています –

+0

あなたはブロックを取る1つのメソッドにレスキューロジックを置くことができ、他のすべてのメソッドではロジック全体をこのメソッドのパラメータとして渡します。しかし、これは汚いと無意味に見えます。実装の詳細については、[this thread](http://stackoverflow.com/questions/16567243/rescue-all-errors-of-a-specific-type-in​​side-a-module)を参照してください –

+1

おめでとうございます。 – engineersmnky

関連する問題