如何使用HTTParty处理错误?

pre*_*yan 70 ruby ruby-on-rails httparty

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

Jor*_*ing 92

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
Run Code Online (Sandbox Code Playgroud)

  • 这个答案没有解决连接失败问题. (41认同)
  • 至于preethinarayan的评论,如果你想要捕捉/拯救错误,你可以总是做一些事情:如果response.code!= 200我将实际做类似的事情来提高blablahblah ... (2认同)

mkl*_*klb 33

这个答案解决了连接失败.如果找不到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
Run Code Online (Sandbox Code Playgroud)

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

  • 永远不要抓住一切 你应该抓住`HTTParty的错误基类. (9认同)

Art*_*jev 13

您也可以使用这种方便的断言方法的success?bad_gateway?用这种方式:

response = HTTParty.post(uri, options)
p response.success?
Run Code Online (Sandbox Code Playgroud)

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

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