Petros Kyriakou
Petros Kyriakou

Reputation: 5343

how to access this kind of hash

I am using RestClient to make a post request and i made it so i an error response back so i can print those error messages in console

i tried the following per the restclient gem documentation

begin
  response = RestClient.post base_uri, params.to_json, content_type: 'application/json', accept: 'application/json'
rescue RestClient::ExceptionWithResponse => err
  error = err.response
  p "this is the error response #{error}"
end

when i print err.response i get the following

"this is the error response {\"error\":{\"message\":\"An active access token must be used to query information about the current us er.\",\"type\":\"OAuthException\",\"code\":2500,\"fbtrace_id\":\"HTzmJ0CcIfd\"}}"

how do i access the message in the above hash to display it in console?

tried

p "this is the error response #{error.message}"

and it gives me "Bad request" - have no idea where it gets that

Upvotes: 1

Views: 95

Answers (2)

tadman
tadman

Reputation: 211740

If you're just looking to output it:

error = JSON.load(err.response)

puts error['error']['message']

You can always format it a bit better:

puts '[Code %d %s] %s' % [
  error['error']['code'],
  error['error']['type'],
  error['error']['message']
]

Note that using puts inside of a Rails process is not going to work very well. You might want to use Rails.logger.debug instead.

Upvotes: 2

AndyV
AndyV

Reputation: 3741

The response you received is in JSON. You'll need to decode the JSON first and then interact with the data. Personally, I like MultiJson for this:

begin
  response = RestClient.post base_uri, params.to_json, content_type: 'application/json', accept: 'application/json'
rescue RestClient::ExceptionWithResponse => err
  error = MultiJson.load(err.response)
  p "this is the error response #{error[:message]}"
end

Upvotes: 1

Related Questions