Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何访问这种散列_Ruby On Rails_Ruby_Ruby On Rails 3_Rest Client - Fatal编程技术网

Ruby on rails 如何访问这种散列

Ruby on rails 如何访问这种散列,ruby-on-rails,ruby,ruby-on-rails-3,rest-client,Ruby On Rails,Ruby,Ruby On Rails 3,Rest Client,我正在使用RestClient发出post请求,我这样做是为了返回错误响应,以便可以在控制台中打印这些错误消息 我根据restclient gem文档尝试了以下操作 begin response = RestClient.post base_uri, params.to_json, content_type: 'application/json', accept: 'application/json' rescue RestClient::ExceptionWithResponse =>

我正在使用RestClient发出post请求,我这样做是为了返回错误响应,以便可以在控制台中打印这些错误消息

我根据restclient gem文档尝试了以下操作

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
当我打印err.response时,我得到以下信息

“这是错误响应{\'error\':{\'message\':\”必须使用活动访问令牌来查询有关当前us的信息
er.\“,”类型\“:”OAuthException\“,”代码\“:2500,\”fbtrace\U id\“:”HTzmJ0CcIfd\“}}}”

如何访问上面散列中的消息以在控制台中显示它

尝试

p“这是错误响应{error.message}”


它给了我一个“错误的请求”-如果你只是想输出它,我不知道它从哪里得到的:

error = JSON.load(err.response)

puts error['error']['message']
您总是可以将其格式设置得更好一些:

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

请注意,在Rails进程中使用
放在内部不会很好地工作。您可能希望改用
Rails.logger.debug

您收到的响应是JSON格式的。您需要首先解码JSON,然后与数据交互。就我个人而言,我喜欢这样:

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

嘿,感谢您尝试上面的响应,但是给了我一个空字符串
“这是错误响应”
这很奇怪。试过puts和Rails.logger.debugah它说它是一个
字符串
啊,我只是更仔细地看了一下内容,答案更新了。如果你用JSON做了很多HTTP调用,试试看。谢谢你,这就成功了!顺便问一下,我什么时候使用Rails.logger.debug?它是否在某处保存日志?它在开发模式下进入
log/development.log
。在生产
debug
级别的消息通常被忽略,以保持日志的整洁。