Python:获取异常的错误消息 [英] Python: Getting the error message of an exception

查看:132
本文介绍了Python:获取异常的错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python 2.6.6中,如何捕获异常的错误消息。



IE:

  response_dict = {}#包含在django视图下响应的信息。 
try:
plan.save()
response_dict.update({'plan_id':plan.id})
除了IntegrityError,e:#包含我自己的自定义异常提升与自定义消息。
response_dict.update({'error':e})
return HttpResponse(json.dumps(response_dict),mimetype =application / json)
/ pre>

这似乎不起作用我得到:

  IntegrityError('不允许冲突',)不是JSON序列化


解决方案

将其通过 str()

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

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


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

解决方案

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.

这篇关于Python:获取异常的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆