Home > Net >  how to access a key after to_json in ruby
how to access a key after to_json in ruby

Time:02-17

I have an except message I want to parse as an JSON object in order to read out a key value pair in it. 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? If I try to print out the value with error['error_code'] I just says 'error_code'

How can I access the value in the error variable?

CodePudding user response:

Thanks to @brcebn and @max I realized I was trying to solve the wrong problem here.

I wrote a customized exception and now I have no problem:

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

...
raise MyError.new("my message", response.code)

finally in my file:

rescue Exception => e
   error_code = e.error_code
end
  • Related