Python: Getting the error message of an exception


Question

In python 2.6.6, how can I capture the error message of an exception.

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")

This doesnt seem to work. I get:

IntegrityError('Conflicts are not allowed.',) is not JSON serializable
1
33
6/9/2015 5:21:29 PM

Accepted Answer

Pass it through str() first.

response_dict.update({'error': str(e)})

Also note that certain exception classes may have specific attributes that give the exact error.

31
12/16/2010 12:32:58 PM

Everything about str is correct, yet another answer: an Exception instance has message attribute, and you may want to use it (if your customized IntegrityError doesn't do something special):

except IntegrityError, e: #contains my own custom exception raising with custom messages.
    response_dict.update({'error': e.message})

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon