【问题标题】:Error patterns in rails, raise "text evaluting to RuntimeError" or raise MyModule::CustomError?rails 中的错误模式,引发“文本评估到 RuntimeError”或引发 MyModule::CustomError?
【发布时间】:2010-09-24 14:11:09
【问题描述】:

问:标题可能问题太大,答案可能是“视情况而定”?但是,提供一些实际案例/示例应该可以帮助像我这样的开发人员认识到何时应用什么。我将从我的特殊情况开始。你会还是不会使用自定义错误类?为什么/为什么不?

欢迎使用下面的其他示例,例如当您使用自己的错误类时。我真的很想知道。

例如:我正在使用httparty 来查询我们的rails Web 服务应用程序以获取一些数据。它使用基本身份验证。我将粘贴测试代码和实现。我的测试应该期待什么,RuntimeErrorSomeCustomError

class MyIntegrationTest < Test::Unit::TestCase
  context "connecting to someapp web service" do
    should "raise not authorized if username is wrong" do
      #get default MyWebserviceInterface instance, overriding username setting
      ws_endpoint = build_integration_object(:username => 'wrong_username')          
      assert_raises RuntimeError do  #TODO error design pattern?
        ws_endpoint.get
      end

    end
  end
end

实现:

class MyWebserviceInterface
  include HTTParty

  #Basic authentication and configurable base_uri
  def initialize(u, p, uri)
    @auth = {:username => u, :password => p}
    @uri = uri
  end

  def base_uri
    HTTParty.normalize_base_uri(@uri)
  end

  def get(path = '/somepath.xml', query_params = {})
    opts = {:base_uri => base_uri, :query => query_params, :basic_auth => @auth}        
    response = self.class.get(path, opts)
    evaluate_get_response(response)
    response.parsed_response
  end

  def evaluate_get_response(response)
  code = response.code
  body = response.body
  if code == 200
    logger.debug "OK - CREATED code #{code}"
  else
    logger.error "expected code 200, got code #{code}. Response body: #{body}"
    #TODO error design pattern? raise the above logged msg or a custom error?
    raise SomeAppIntegration::Error(code, body)
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby design-patterns error-handling httparty


    【解决方案1】:

    在大多数情况下,我会从不RuntimeError 解救或提高。这可能与您的代码完全无关。最好使用自定义异常。

    通常,只要在库的常量中命名错误,就可以随意调用错误。例如,如果某人的用户名错误,您可以将 YourApp::InvalidUsername 作为异常对象,其定义如下:

    module YourApp
      class InvalidUsername < StandardError
        def message
          super("Yo dawg, you got your username wrong all up in here")
        end
      end
    

    结束

    当您raise YourApp::InvalidUsername 时,您会看到该消息出现。

    【讨论】:

    • 从来没有?根据我的经验,alwaysnever 很少是最好的规则。但我同意 rescuing from a RunimeError 是错误的,在这些情况下不应抛出 RuntimeError。
    • @oma 查看 RuntimeError 的文档ruby-doc.org/core-2.2.0/RuntimeError.html 这种类型的异常非常普遍。如果你只是在拯救任何东西,拯救错误的好处就会大大降低。文档中的示例引发了一个 RuntimeError 尝试修改冻结数组。拯救这样的东西不是一个好主意。您可以设想挽救它,因为有一段代码“不会失败”,但在这种情况下,我会记录异常,以便稍后修复它。
    • 这是不久前的事了。我完全同意我们不应该为 RuntimeError 提供救援。我仍然经常使用 raise "something",但从不使用救援
    猜你喜欢
    • 2012-09-20
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    相关资源
    最近更新 更多