user3033467 user3033467 - 6 months ago 20
Ruby Question

How to serialize Exception

According to ruby-doc and apidock, you can serialize and deserialize an exception using

to_json
and
json_create
.

But after having wasted some time trying to use them, I still haven't found a way.

Calling
exc.to_json
gives me an empty hash, and
Exception.json_create(hash)
gives me this error:
undefined method 'json_create' for Exception:Class


I guess I could easily recreate those functions since the source is available, but I'd rather understand what I'm doing wrong... Any idea?

Answer

The JSON module doesn't extend Exception by default. You have to require "json/add/exception". I'm not sure if this is documented anywhere:

require "json/add/exception"

begin
  nil.foo
rescue => exception
  ex = exception
end

puts ex.to_json
# => {"json_class":"NoMethodError","m":"undefined method `foo' for nil:NilClass","b":["prog.rb:5:in `<main>'"]}

Check out ext/json/lib/json/add in the Ruby source to see which classes work this way. If you do require "json/add/core" it will load JSON extensions for Date, DateTime, Exception, Range, Regexp, Struct, Symbol, and Time.

Comments