0

Q:タイトルが大きすぎる質問で、答えは「場合による」ではないでしょうか? ただし、いくつかの実用的なケース/例を提供することは、私のような開発者がいつ何を適用するかを認識するのに役立ちます。私は自分の特定の状況から始めます。カスタム エラー クラスを使用しますか、または使用しませんか? なぜ/なぜしないのですか?

独自のエラー クラスを使用する場合など、以下のような他の例を歓迎します。私は本当に疑問に思っています。

例: httpartyを使用して、Rails Web サービス アプリにデータをクエリしています。基本認証を使用します。テストコードと実装の両方を貼り付けます。私のテストでは、RuntimeErrorまたはSomeCustomErrorの何を期待する必要がありますか?

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
4

1 に答える 1

2

ほとんどの場合、私はからレスキューしたりレイズしたりしません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そのメッセージが表示されたら。

于 2010-09-24T15:00:33.883 に答える