Python:获取异常的错误消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4460669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Getting the error message of an exception
提问by Hellnar
In python 2.6.6, how can I capture the error message of an exception.
在 python 2.6.6 中,如何捕获异常的错误消息。
IE:
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
采纳答案by Ignacio Vazquez-Abrams
Pass it through str()first.
先通过吧str()。
response_dict.update({'error': str(e)})
Also note that certain exception classes may have specific attributes that give the exact error.
另请注意,某些异常类可能具有给出确切错误的特定属性。
回答by khachik
Everything about stris correct, yet another answer: an Exceptioninstance has messageattribute, and you may want to use it (if your customized IntegrityErrordoesn't do something special):
一切str都是正确的,还有另一个答案:Exception实例具有message属性,您可能想要使用它(如果您的自定义IntegrityError没有做一些特殊的事情):
except IntegrityError, e: #contains my own custom exception raising with custom messages.
response_dict.update({'error': e.message})
回答by Don
You should use unicodeinstead of stringif you are going to translate your application.
如果您要翻译您的应用程序,您应该使用unicode而不是string。
BTW, Im case you're using json because of an Ajax request, I suggest you to send errors back with HttpResponseServerErrorrather than HttpResponse:
顺便说一句,如果您因为 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")
and then manage errors in your Ajax procedure. If you wish I can post some sample code.
然后管理 Ajax 过程中的错误。如果您愿意,我可以发布一些示例代码。
回答by Rick Graves
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' )

