[英]how to access a key after to_json in ruby
I have an except message I want to parse as an JSON object in order to read out a key value pair in it.我有一条例外消息,我想将其解析为 JSON object 以便读出其中的键值对。 Message looks like
消息看起来像
{"message":"my message","error_code":404}
code looks like this:代码如下所示:
rescue Exception => e
puts e
error = e.to_json
error_json = JSON.parse(error)
error_code = JSON.parse(error_json)['error_code']
end
seems odd to me that I have to parse this twice.对我来说似乎很奇怪,我必须解析两次。 Shouldn't
error
already be a JSON object? error
不应该已经是 JSON object 了吗? If I try to print out the value with error['error_code'] I just says 'error_code'如果我尝试使用 error['error_code'] 打印出值,我只是说'error_code'
How can I access the value in the error
variable?如何访问
error
变量中的值?
Thanks to @brcebn and @max I realized I was trying to solve the wrong problem here.感谢@brcebn 和@max,我意识到我试图在这里解决错误的问题。
I wrote a customized exception and now I have no problem:我写了一个自定义的异常,现在我没有问题了:
my_exception.rb我的异常.rb
class MyError < StandardError
attr_reader :message
attr_reader :error_code
def initialize(msg, error_code)
@msg = msg
@error_code = error_code
super(msg)
end
end
calling the exception in my_service.rb在 my_service.rb 中调用异常
...
raise MyError.new("my message", response.code)
finally in my file:最后在我的文件中:
rescue Exception => e
error_code = e.error_code
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.