如何使用 HTTParty 处理错误? [英] How can I handle errors with HTTParty?

查看:81
本文介绍了如何使用 HTTParty 处理错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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::Response 有一个 code 属性,它包含 HTTP 响应的状态代码.它以整数形式给出.所以,像这样:

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

这篇关于如何使用 HTTParty 处理错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆