如何使用 HTTParty 处理错误?

问题描述 投票:0回答:3

我正在开发一个使用 HTTParty 发出 HTTP 请求的 Rails 应用程序。如何使用 HTTParty 处理 HTTP 错误?具体来说,我需要捕获 HTTP 502 和 503 以及其他错误,例如连接被拒绝和超时错误。

ruby-on-rails ruby httparty
3个回答
98
投票

HTTPParty::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

48
投票

This answer addresses connection failures. 如果找不到 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

有关更多信息,请参阅:this github issue


26
投票

您还可以像这样使用像

ok?
bad_gateway?
这样方便的谓词方法:

response = HTTParty.post(uri, options)
response.success?

所有可能的响应的完整列表可以在

Rack::Utils::HTTP_STATUS_CODES
常量下找到。

© www.soinside.com 2019 - 2024. All rights reserved.