gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:01:41 25 4
gpt4 key购买 nike

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_1method_2、...、method_n)中以相同的方式进行救援。我坚持想出一个漂亮而干净的解决方案,不需要复制救援代码块。你能帮我吗?

最佳答案

如何使用 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

关于ruby - 在类内的每个方法中添加 rescue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39507187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com