如何使用HTTParty处理错误?

79

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

3个回答

101

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

谢谢!这正是我计划要做的。不知道是否有其他处理错误的方法。 - preethinarayan
51
这个回答没有涉及连接失败的问题。 - gtd
2
关于preethinarayan的评论,如果你想要捕获/解决错误,你可以像这样做: 如果响应代码不是200,则引发blablahblah我实际上也会做类似的事情... - user435779
响应代码总是返回200,如果在应用程序中处理了错误。如何解决这个问题? - Infant Dev

50

本答案解决连接失败问题。 如果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问题


12
不要想着抓住所有东西,你应该捕获HTTParty的错误基类。 - Linus Oleander
也许想法是在HTTParty代码中捕获错误。HTTParty可能会引发不是HTTParty::Errors的错误。 - B Seven
1
如果完全没有网络,我会收到一个“SocketError”错误提示,这是需要注意的。你可以尝试拔掉以太网电缆来观察这种情况。 - Kris
1
我使用suspenders中的HTTP_ERRORS,https://github.com/thoughtbot/suspenders/blob/master/templates/errors.rb和`HTTParty::Error` https://www.rubydoc.info/github/jnunemaker/httparty/HTTParty/Error,例如`rescue HTTParty::Error, *HTTP_ERRORS`。 - localhostdotdev

28

您还可以像这样使用方便的谓词方法,例如ok?bad_gateway?

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

所有可能的响应列表可以在Rack::Utils::HTTP_STATUS_CODES常量下找到。


2
我刚刚阅读了这条评论,它也对我有很大帮助!https://github.com/jnunemaker/httparty/issues/456#issuecomment-498778386 - kangkyu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接