【问题标题】:Abstracting exception checking抽象异常检查
【发布时间】:2011-05-19 00:55:28
【问题描述】:

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

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

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

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

【问题讨论】:

  • 这是用于模型、控制器还是其他什么?

标签: ruby-on-rails ruby exception-handling refactoring


【解决方案1】:

在控制器中,我使用了 rescue_from 功能。很干:

class HelloWorldController < ApplicationController
  rescue_from ActiveRecord::RecordNotFound, :with => :handle_unfound_record

  def handle_unfound_record
    # Exception handling...
  end

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 2017-05-01
      • 1970-01-01
      相关资源
      最近更新 更多