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:
{
"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
The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (for example, malformed request syntax, invalid request message framing, or deceptive request routing).
The HTTP status 400 – bad request indicates that the request sent to the server is invalid or corrupted. Just like other 4xx status codes, a 400 bad request is a client-side issue. It can be caused by malformed request syntax, invalid request message framing, or deceptive request routing.
The 400 Bad request status code indicates that the server was unable to process the request due to invalid information sent by the client.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With