gpt4 book ai didi

ruby-on-rails - 抽象异常检查

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

我有一系列使用相同异常处理的方法。

如何将异常检查抽象为一个单独的函数?

请参见下面的示例,非常感谢您的帮助!

def a
code
begin
rescue 1...
rescue 2...
rescue 3...
rescue 4...
end
end

def b
code
begin
rescue 1...
rescue 2...
rescue 3...
rescue 4...
end
end

最佳答案

最简单的解决方案是将您的代码作为一个 block 传递给一个方法,并在开始/救援表达式中产生它:

def run_code_and_handle_exceptions
begin
yield
rescue 1...
rescue 2...
rescue 3...
rescue 4...
end
end

# Elsewhere...
def a
run_code_and_handle_exceptions do
code
end
end
# etc...

您可能想要一个比 run_code_and_handle_exceptions 更简洁的方法名称!

关于ruby-on-rails - 抽象异常检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4333749/

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