Search code examples
ruby-on-railsrubyruby-on-rails-3rest-client

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


Solution

  • 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.