Reading the body of a 400 response?
Asked Answered
G

1

10

I am trying to read the body of a 400 response with the rest-client gem. The problem is that rest-client responds to 400 by throwing it as an error, so I can't figure out any way to get the body text.

Here's the motivating example. Consider this call to the facebook graph API:

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

If the access_token is expired or invalid, facebook does two things:

  1. Returns a 400 Bad Request HTTP response
  2. Returns JSON in the response body with more info, like this:
{
   "error": {
      "message": "The access token could not be decrypted",
      "type": "OAuthException",
      "code": 190
   }
}

Because 400 response raises an Error, I can't figure out how to get the body of the response. That is, eg, if I run the GET request above in curl or in my browser, I can see the body, but I can't figure out how to access it in restclient. Here's an example:

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
Gavrila answered 13/5, 2014 at 5:20 Comment(0)
G
27

From 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

You can rewrite your code like:

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)

Or just use RestClient::Exception#http_body to get the response body from the exception. (It's just a shortcut).

Gormand answered 13/5, 2014 at 5:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.