Ruby-on-rails 如何使用 HTTParty 处理错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7909596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:15:44  来源:igfitidea点击:

How can I handle errors with HTTParty?

ruby-on-railsrubyhttparty

提问by preethinarayan

I'm working on a Rails application using HTTParty to make HTTP requests. How can I handle HTTP errors with HTTParty? Specifically, I need to catch HTTP 502 & 503 and other errors like connection refused and timeout errors.

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

回答by Jordan Running

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

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

回答by mklb

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

此答案解决了连接失败问题。如果未找到 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

For more information see: this github issue

有关更多信息,请参阅:此 github 问题

回答by Artur Beljajev

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

您还可以使用这样方便的谓词方法success?bad_gateway?以这种方式:

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

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

可以在Rack::Utils::SYMBOL_TO_STATUS_CODE常量下找到可能响应的完整列表。