加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:58:32 所属栏目:百科 来源:网络整理
导读:我有一系列使用相同异常处理的方法. 如何将异常检查抽象为单独的函数? 请参阅下面的示例,非常感谢您的帮助! def a code begin rescue 1... rescue 2... rescue 3... rescue 4... endenddef b code begin rescue 1... rescue 2... rescue 3... rescue 4...
我有一系列使用相同异常处理的方法.

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

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

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

解决方法

最简单的解决方案是将代码作为块传递给方法,并在开始/救援表达式中将其生成:

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更简洁的方法名称!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读