[英]How can I handle errors with HTTParty?
我正在開發一個使用 HTTParty 發出 HTTP 請求的 Rails 應用程序。 如何使用 HTTParty 處理 HTTP 錯誤? 具體來說,我需要捕獲 HTTP 502 和 503 以及其他錯誤,例如連接被拒絕和超時錯誤。
HTTParty::Response的實例有一個code
屬性,其中包含 HTTP 響應的狀態代碼。 它以整數形式給出。 所以,像這樣:
response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
case response.code
when 200
puts "All good!"
when 404
puts "O noes not found!"
when 500...600
puts "ZOMG ERROR #{response.code}"
end
此答案解決了連接失敗問題。 如果未找到 URL,狀態代碼將無濟於事。 像這樣拯救它:
begin
HTTParty.get('http://google.com')
rescue HTTParty::Error
# don´t do anything / whatever
rescue StandardError
# rescue instances of StandardError,
# i.e. Timeout::Error, SocketError etc
end
有關更多信息,請參閱:此 github 問題
您還可以使用諸如success?
類的方便的謂詞方法success?
或bad_gateway?
通過這種方式:
response = HTTParty.post(uri, options)
p response.success?
可以在Rack::Utils::SYMBOL_TO_STATUS_CODE
常量下找到可能響應的完整列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.