代码之家  ›  专栏  ›  技术社区  ›  oma

rails中的错误模式,引发“text evaluting to RuntimeError”或引发MyModule::CustomError?

  •  0
  • oma  · 技术社区  · 14 年前

    问: 题目可能太大了,答案可能是“视情况而定”?然而,提供一些实际的案例/例子应该可以帮助开发人员,比如我,认识到什么时候应该应用什么。我先从我的特殊情况说起。是否使用自定义错误类?为什么?

    下面的例子也很受欢迎,比如当您使用自己的错误类时。我真的很想知道。

    前任: 我在用 httparty 查询rails web服务应用程序以获取一些数据。它使用基本身份验证。我将粘贴测试代码和实现。我的测试应该期待什么, 访问违例 ?

    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
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   Ryan Bigg Andrés Bonilla    14 年前

    从未 救出或升起 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 你会看到这个消息出现。