Python:获取异常的错误消息

Hel*_*nar 33 python django exception-handling

在python 2.6.6中,我如何捕获异常的错误消息.

IE:

response_dict = {} # contains info to response under a django view.
try:
    plan.save()
    response_dict.update({'plan_id': plan.id})
except IntegrityError, e: #contains my own custom exception raising with custom messages.
    response_dict.update({'error': e})
return HttpResponse(json.dumps(response_dict), mimetype="application/json")
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用.我明白了:

IntegrityError('Conflicts are not allowed.',) is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 31

str()首先通过它.

response_dict.update({'error': str(e)})
Run Code Online (Sandbox Code Playgroud)

另请注意,某些异常类可能具有可提供确切错误的特定属性.