Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 为什么包括可救援模块不';不行?_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 为什么包括可救援模块不';不行?

Ruby on rails 为什么包括可救援模块不';不行?,ruby-on-rails,ruby,Ruby On Rails,Ruby,MyKlass是纯ruby对象,但在Rails应用程序中定义 若我试图在rails控制台中调用MyKlass实例,然后应用于它的方法,该方法肯定会引发异常,那个么除了预期要挽救的错误之外,并没有什么事情发生 以下是它的使用方法: class MyKlass include ActiveSupport::Rescuable rescue_from Exception do return "rescued" end #other stuff end 不言而喻,营救例外

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


若我试图在rails控制台中调用MyKlass实例,然后应用于它的方法,该方法肯定会引发异常,那个么除了预期要挽救的错误之外,并没有什么事情发生

以下是它的使用方法:

class MyKlass

  include ActiveSupport::Rescuable

  rescue_from Exception do
    return "rescued"
  end

  #other stuff
end

不言而喻,营救例外是一种犯罪。

我认为营救的意义在于我不需要在每种方法中都包括营救。我有20个,你可以把一个救援逻辑放到一个方法中,这个方法需要一个块,然后把整个逻辑作为一个参数传递给这个方法。但这看起来肮脏而毫无意义。有关实现详细信息,请参阅“捕获”它的关联:)
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