Railsのエラーパターン、「RuntimeErrorに評価するテキスト」を上げる、またはMyModule :: CustomErrorを上げますか?
-
05-10-2019 - |
質問
Q: タイトルはおそらくあまりにも大きな質問であり、答えはおそらく「それは依存する」でしょうか?ただし、いくつかの実用的なケース/例を提供することは、私のような開発者がいつ何を適用するかを認識するのに役立つはずです。特定の状況から始めます。カスタムエラークラスを使用しませんか、それとも使用しませんか?なぜ/なぜそうしないのですか?
以下の例として他の例は、独自のエラークラスを使用するときのように歓迎されます。本当に疑問に思っています。
元: 私は使用しています httparty Rails Webサービスアプリをいくつかのデータに照会します。基本認証を使用します。テストコードと実装の両方を貼り付けます。私のテストは何を期待すべきですか、 ランタイムエラー また 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
解決
ほとんどの場合、私はそうします 一度もない 救助または育てます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
そのメッセージが表示されることがわかります。
所属していません StackOverflow