2016-09-28 39 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

相关问题