1
問:標題可能太大的問題,答案可能是「它取決於」?但是,提供一些實際案例/示例應該可以幫助像我這樣的開發人員識別何時應用什麼。我將從我的特殊情況開始。你會或不會使用自定義錯誤類?爲什麼/爲什麼不?Rails中的錯誤模式,引發「文本評估RuntimeError」或引發MyModule :: CustomError?
歡迎使用下面的其他示例,例如當您使用自己的錯誤類時。我真的很想知道。
例如:我正在使用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
從來沒有?根據我的經驗,_always_和_never_很少是最好的規則。但我同意,從RunimeError中_rescuing_是錯誤的,並且RuntimeError不應該在這些情況下拋出。 – oma 2010-09-27 07:30:17
@oma查看RuntimeError的文檔http://ruby-doc.org/core-2.2.0/RuntimeError.html這種類型的異常非常普遍。如果你正在拯救任何東西,拯救錯誤的好處大大減少。文檔中的示例引發RuntimeError嘗試修改凍結數組。拯救類似的東西並不是一個好主意。你可以設想挽救它,因爲有一塊代碼「不能失敗」,但在這種情況下,我會記錄異常,以便稍後修復它。 – unflores 2016-08-10 09:37:05
這是前一陣子。我完全同意我們不應該爲RuntimeError進行救援。我仍然經常使用提高「某種東西」,但從來沒有進行過救援 – oma 2016-10-27 01:44:02