微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby – 阅读400响应的主体?

我试图用rest-client gem读取400响应的主体.问题是,rest-client通过将其作为错误进行响应来响应400,所以我无法找出任何获取正文的方法.

这是激励性的例子.考虑这个对facebook图API的调用

JSON.parse(RestClient.get("https://graph.facebook.com/me?fields=id,email,first_name,last_name&access_token=#{access_token}"))

如果access_token过期或无效,facebook会做两件事:

>返回400 Bad Request HTTP响应
>在响应正文中返回JSON,其中包含更多信息,如下所示:

{
   "error": {
      "message": "The access token Could not be decrypted","type": "OAuthException","code": 190
   }
}

因为400响应引发了错误,我无法弄清楚如何获得响应的主体.也就是说,例如,如果我在curl或浏览器中运行上面的GET请求,我可以看到正文,但我无法弄清楚如何在restclient中访问它.这是一个例子:

begin
  fb_response = JSON.parse(RestClient.get("https://graph.facebook.com/me?fields=id,last_name&access_token=#{access_token}"))
rescue => e
  # 400 response puts me here
  # How can I get the body of the above response Now,so I can get details on the error?
  # eg,was it an expired token?  A malformed token?  Something else?
end

解决方法

rest-client documentation开始:

Exceptions

for other cases,a RestClient::Exception holding the Response will be raised; a specific exception class will be thrown for kNown error codes

begin
  RestClient.get 'http://example.com/resource'
rescue => e
  e.response
end

您可以重写您的代码,如:

body = begin
  RestClient.get("https://graph.facebook.com/me?fields=id,last_name&access_token=#{access_token}")
rescue => e
  e.response.body
end
fb_response = JSON.parse(body)

或者只使用RestClient::Exception#http_body从异常中获取响应正文. (这只是一条捷径).

原文地址:https://www.jb51.cc/ruby/269233.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐