Python:获取异常的错误消息

时间:2010-12-16 12:19:17

标签: 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")

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

IntegrityError('Conflicts are not allowed.',) is not JSON serializable

5 个答案:

答案 0 :(得分:30)

首先通过str()

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

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

答案 1 :(得分:4)

关于str的所有内容都是正确的,还有另一个答案:Exception实例具有message属性,您可能想要使用它(如果您的自定义IntegrityError没有'做一些特别的事情):

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

答案 2 :(得分:3)

如果您要翻译申请,则应使用unicode代替string

BTW,我是因为Ajax请求你正在使用json,我建议你用HttpResponseServerError而不是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")

然后管理Ajax过程中的错误。 如果您希望我可以发布一些示例代码。

答案 3 :(得分:0)

这对我有用:

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

答案 4 :(得分:0)

假设你提出这样的错误

raise someError("some error message")

和 'e' 被捕获错误实例

str(e) 返回:

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

但如果你只想要“一些错误信息”

e.detail

会给你那个(实际上给你一个 str 列表,其中包括“一些错误消息”)

相关问题