2016-04-15 30 views
1

我使用RESTClient实现做一个POST请求和我做到了,所以我的错误响应回来,所以我可以在控制台如何访问这种散列

打印这些错误信息,我试图按照RESTClient实现宝石以下文档

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我得到以下

"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\"}}"

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

试图

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

,这让我"Bad request" - 不知道从哪里它获取

回答

2

如果你只是希望它输出:

error = JSON.load(err.response) 

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

你可以总是格式化好一点:

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

请注意,在Rails进程中使用puts不会很好。您可能需要改用Rails.logger.debug

+0

嘿感谢响应试过以上,但给我一个空字符串'“这是错误响应”'这是奇怪。尝试使用put和Rails.logger.debug –

+0

我该如何检查? –

+0

啊它说它是一个'string' –

1

您收到的回复是JSON。您需要先解码JSON然后与数据交互。就个人而言,我喜欢MultiJson此:

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