2010-12-16 107 views
32

在python 2.6.6中,如何捕獲異常的錯誤消息。Python:獲取異常的錯誤消息

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 
+1

「這似乎沒有工作。」 - 它應該做什麼,不做什麼? – khachik 2010-12-16 12:22:38

+0

您使用的是哪個版本的Python? – infrared 2010-12-16 12:22:48

+0

你好,我已經更新了我的問題。謝謝 – Hellnar 2010-12-16 12:25:48

回答

28

先通過str()

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

另請注意,某些異常類可能具有給出確切錯誤的特定屬性。

+4

但unicode失敗,不是嗎? – 2014-01-16 09:46:40

4

一切有關str是正確的,另一種答案:一個Exception實例有message屬性,您可能希望使用它(如果您的自定義IntegrityError沒有做一些特別的東西):

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

自Python 2.6以來,不推薦使用BaseException.message屬性。參見:http://stackoverflow.com/questions/1272138/baseexception-message-deprecated-in-python-2-6 – bosgood 2012-10-22 17:45:34

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程序管理錯誤。 如果您希望我可以發佈一些示例代碼。

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') 
相關問題