2010-12-16 18 views
32

पायथन 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") 

यह does not काम करने लगते हैं। मुझे मिलता है:

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

"यह does not काम करने के लिए लग रहे हैं।" - यह क्या करना चाहिए और क्या नहीं करता? – khachik

+0

पाइथन का कौन सा संस्करण आप उपयोग कर रहे हैं? – infrared

+0

हैलो, मैंने अपना प्रश्न अपडेट किया है। धन्यवाद – Hellnar

उत्तर

28

इसे str() के माध्यम से पहले पास करें।

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

यह भी ध्यान रखें कि कुछ अपवाद वर्गों में विशिष्ट विशेषताओं हो सकती हैं जो सटीक त्रुटि देते हैं।

+4

लेकिन यह यूनिकोड के लिए विफल रहता है, नहीं? –

4

सब कुछ के बारे में str सही है, अभी तक एक और जवाब: एक Exception उदाहरण message विशेषता है, और आप इसे उपयोग करने के लिए (यदि अपने अनुकूलित IntegrityError कुछ खास नहीं है) कर सकते हैं:

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

बेसException.message विशेषता को Python 2.6 के बाद बहिष्कृत कर दिया गया है। देखें: http://stackoverflow.com/questions/1272138/baseexception-message-deprecated-in-python-2-6 – bosgood

3

आप चाहिए यदि आप अपने आवेदन का अनुवाद करने जा रहे हैं तो string के बजाय unicode का उपयोग करें।

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

और फिर अपने अजाक्स प्रक्रिया में त्रुटियों का प्रबंधन। यदि आप चाहें तो मैं कुछ नमूना कोड पोस्ट कर सकता हूं।

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') 
संबंधित मुद्दे