Python:获取异常的错误消息

37 投票
5 回答
56773 浏览
提问于 2025-04-16 08:37

在Python 2.6.6中,我该如何获取异常的错误信息呢?

比如:

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 个回答

3

如果你打算翻译你的应用程序,建议使用 unicode 而不是 string

顺便说一下,如果你因为 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

关于 str 的一切都是正确的,不过还有另一个答案:一个 Exception 实例有一个 message 属性,你可能想要使用它(如果你自定义的 IntegrityError 没有做什么特别的事情的话):

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

先用 str() 把它转换一下。

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

另外要注意,有些异常类可能会有特定的属性,可以提供更准确的错误信息。

撰写回答