37

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
Al Sweigart
  • 11,566
  • 10
  • 64
  • 92
Hellnar
  • 62,315
  • 79
  • 204
  • 279

5 Answers5

36

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
3

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})
khachik
  • 28,112
  • 9
  • 59
  • 94
  • 13
    The BaseException.message attribute has been deprecated since Python 2.6. See: http://stackoverflow.com/questions/1272138/baseexception-message-deprecated-in-python-2-6 – bosgood Oct 22 '12 at 17:45
3

You should use unicode instead of string if you are going to translate your application.

BTW, Im case you're using json because of an Ajax request, I suggest you to send errors back with HttpResponseServerError rather than HttpResponse:

from django.http import HttpResponse, HttpResponseServerError
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.
    return HttpResponseServerError(unicode(e))

return HttpResponse(json.dumps(response_dict), mimetype="application/json")

and then manage errors in your Ajax procedure. If you wish I can post some sample code.

Don
  • 16,928
  • 12
  • 63
  • 101
1

Suppose you raise error like this

raise someError("some error message")

and 'e' is catched error instance

str(e) returns:

[ErrorDetail(string='some error message', code='invalid')]

but if you want "some error message" only

e.detail

will gives you that (actually gives you a list of str which includes "some error message")

-1

This works for me:

def getExceptionMessageFromResponse( oResponse ):
    #
    '''
    exception message is burried in the response object,
    here is my struggle to get it out
    '''
    #
    l = oResponse.__dict__['context']
    #
    oLast = l[-1]
    #
    dLast = oLast.dicts[-1]
    #
    return dLast.get( 'exception' )
Rick Graves
  • 517
  • 5
  • 11