ruby – 在类中的每个方法中添加rescue

class A
  def a_method
    #..
  end
end

class B < A
  def method_1
    # ...
    a_method
  end

   def method_2
    # ...
    a_method
  end

  # ...

  def method_n
    # ...
    a_method
  end
end

a_method偶尔会抛出一个AException.

我想从那个例外中解救,比如:

class B < A
  def method_1
    # ...
    a_method
  rescue AException => e
    p e.message
  end

  # ...
end

我想在B类(method_1,method_2,…,method_n)中的每个方法中以相同的方式进行挽救.我坚持找出一个漂亮而干净的解决方案,不需要复制救援代码块.你能帮帮我吗?

解决方法

如何使用块:
class B < A
  def method_1
    # some code here which do not raised an exception
    with_rescue do
      # method which raised exception
      a_method
    end
  end

  def method_2
    with_rescue do
      # ...
      a_method
    end
  end

  private 

  def with_rescue
    yield
  rescue => e
    ...
  end
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...