maicher maicher - 2 months ago 9
Ruby Question

Add rescue in each method inside a class

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


The
a_method
ocassionally throws an AException.

I want to rescue from that exception, like:

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

# ...
end


I want to rescue the same way in each methods inside class B (
method_1
,
method_2
, ...,
method_n
). I'm stuck on figuring out a nice and clean solution, that would not require to duplicate the rescue code block. Can you help me with that?

Answer

How about to use a block:

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
Comments