阅读400响应的主体?

 月雨淅淅 发布于 2023-01-15 14:23

我试图用rest-client宝石阅读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,email,first_name,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

Arie Xiao.. 25

来自rest-client文档:

例外

对于其他情况,将引发一个包含Response的RestClient :: Exception; 将针对已知错误代码抛出特定的异常类

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

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

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

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

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有