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