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)
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问题
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常量下找到可能响应的完整列表.
| 归档时间: |
|
| 查看次数: |
35635 次 |
| 最近记录: |