如何使用 HTTParty 处理错误?

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

47434 次浏览

An instance of HTTParty::Response has a code attribute which contains the status code of the HTTP response. It's given as an integer. So, something like this:

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

This answer addresses connection failures. If a URL isn´t found the status code won´t help you. Rescue it like this:

 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

For more information see: this github issue

You can also use such handy predicate methods as success? or bad_gateway? like this:

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

Full list of possible responses can be found under Rack::Utils::SYMBOL_TO_STATUS_CODE constant.