[英]Where to write begin rescue in Ruby (on Rails)
當我寫 ruby 或 (rails) 時,我應該在哪里寫關於 http 請求的begin
和rescue
(或者一般來說,在哪里寫 begin rescue)?
我說的是控制器、模型或模塊。
例如,我寫了這樣的代碼。
module
module WhateverModule
def get_list
http, uri_path, headers = set_request("whatever_api_url")
http.get(uri_path, headers)
end
#codes continue below
end
然后,我經常將begin
和rescue
代碼放在控制器上。
controller
begin
api_list = get_list
rescue => exception
# do whatever I need to do to handle exceptions
p "exception happened!"
end
但我的 PR 審閱者一直說“你應該寫這樣的代碼”
module
module WhateverModule
def get_list
http, uri_path, headers = set_request("whatever_api_url")
begin
http.get(uri_path, headers)
rescue => exception
p "exception happend!"
end
end
#codes continue below
end
我的問題是,哪一個是正確的(或干凈或更好)? 關於從哪里begin
和rescue
有什么普遍的共識嗎?
謝謝
我會爭辯說,在使用rescue
塊時,遵循兩個准則是一種常見的模式:
rescue
塊放置在盡可能少的行數周圍。 通常,這應該只有一行。 這當然取決於您的代碼,但總的來說,特定方法會引發異常。 如果可能, rescue
塊應該只在該塊周圍。 這使得調試和重構變得更加容易。rescue
塊時,請准確命名您希望發生的那些異常。 否則,您可能會發現意外的錯誤(語法錯誤或nil
上的方法調用)。 又是什么讓調試變得更加困難。在您的示例中,我同意 PR 審閱者的觀點,但我會添加可能發生且我想要處理的特定異常。 例如像這樣:
def get_list
http, uri_path, headers = set_request("whatever_api_url")
begin
http.get(uri_path, headers)
rescue Net::HTTPNotFound => e
# handle page not found
rescue Net::HTTPForbidden => e
# handle invalid credentials
rescue Net::HTTPServerError, Net::HTTPServerException
# handle server error
end
end
當然,如何處理異常以及是否有可能取決於您的應用程序。 因此,沒有硬性規定,只有指導方針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.