user3033467 user3033467 - 1 year ago 115
Ruby Question

How to serialize Exception

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


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

gives me an empty hash, and
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 Source

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"

rescue => exception
  ex = exception

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download