为什么包括Rescuable模块不起作用?

时间:2016-09-28 13:56:26

标签: ruby-on-rails ruby

class MyKlass

  include ActiveSupport::Rescuable

  rescue_from Exception do
    return "rescued"
  end

  #other stuff
end

MyKlass是纯ruby对象,但在Rails应用程序中定义。

如果我尝试在rails控制台中调用MyKlass实例然后应用它当然应该引发Exception的方法,除了预期要获救的错误之外没有任何其他事情发生。

1 个答案:

答案 0 :(得分:2)

以下是它应该如何使用:

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是犯罪行为。