Search code examples
ruby

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?


Solution

  • The JSON module doesn't extend Exception by default. You have to require "json/add/exception". This is documented in the JSON Additions section of the Ruby JSON module docs.

    require "json/add/exception"
     
    begin
      nil.foo
    rescue => exception
      ex = exception
    end
    
    json = ex.to_json
    puts 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, OpenStruct, Range, Regexp, Struct, Symbol, Time, and others.

    To reverse the process, you can pass the create_additions: true option to JSON.parse:

    p JSON.parse(json, create_additions: true)
    # => #<NoMethodError: undefined method `foo' for nil:NilClass
    #
    #      nil.foo
    #         ^^^^>