2016-09-28 63 views
1
class MyKlass 

    include ActiveSupport::Rescuable 

    rescue_from Exception do 
    return "rescued" 
    end 

    #other stuff 
end 

MyKlass是純ruby對象,但在Rails應用程序中定義。爲什麼包含Rescuable模塊不起作用?

如果我嘗試在rails控制檯中調用MyKlass實例,然後將其應用於該方法,該方法肯定應該引發異常,除了預期將被解救的錯誤之外,沒有任何事情發生。

回答

1

下面是它應該如何使用:

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 

不言而喻,即搶救Exception是一種犯罪行爲。

+0

我雖然說rescue_from的意義在於我不需要在每種方法中包含救援。我有其中20個 –

+0

你可以把一個拯救的邏輯放入一個方法中,該方法需要一個塊,並且在每一個其他方法中傳遞整個邏輯作爲這個方法的一個參數。但是這看起來很髒並且毫無意義。看到[這個線程](http://stackoverflow.com/questions/16567243/rescue-all-errors-of-a-specific-type-in​​side-a-module)的實現細節 –

+1

祝賀你「catched」它:) – engineersmnky

相關問題