title: How to serialize an Exception
body: <p>When I try to serialize an exception using <code>json.dump</code>, I get errors like</p>
  
  <pre><code>TypeError: IOError('socket error', error(61, 'Connection refused')) is not JSON serializable
  </code></pre>
  
  <p>and</p>
  
  <pre><code>TypeError: error(61, 'Connection refused') is not JSON serializable
  </code></pre>
  
  <p>The <code>__dict__</code> field of exceptions is <code>{}</code> (this is why <a href="https://stackoverflow.com/q/3768895/850781">How to make a class JSON serializable</a> does not help me: the answers there assume that <code>__dict__</code> contains all the necessary information, they also assume that I have control over the class to be serialized).</p>
  
  <p>Is there something more intelligent that saving <code>str(exn)</code>?</p>
  
  <p>I would prefer a human-readable text representation (not <code>pickle</code>).</p>
  
  <p>PS. Here is what I came up with:</p>
  
  <pre><code>def exception_as_dict(ex):
      return dict(type=ex.__class__.__name__,
                  errno=ex.errno, message=ex.message,
                  strerror=exception_as_dict(ex.strerror)
                  if isinstance(ex.strerror,Exception) else ex.strerror)
  
  json.dumps(exception_as_dict(err),indent=2)
  {
    "errno": "socket error", 
    "type": "IOError", 
    "strerror": {
      "errno": 61, 
      "type": "error", 
      "strerror": "Connection refused"
    }
  }
  </code></pre>