ruby 为什么包含可救援模块不起作用?

33qvvth1  于 2023-08-04  发布在  Ruby
关注(0)|答案(1)|浏览(92)
class MyKlass

  include ActiveSupport::Rescuable

  rescue_from Exception do
    return "rescued"
  end

  #other stuff
end

字符串
MyKlass是一个纯粹的Ruby对象,但在Rails应用程序中定义。
如果我尝试在rails控制台中调用MyKlass示例,然后应用于它的方法,当然应该引发Exception,除了错误预期被挽救之外,什么也不会发生。

ztigrdn8

ztigrdn81#

以下是它应该如何使用:

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是一种犯罪。

相关问题