2014-10-30 163 views
1

多googli搜索找出後去上什麼,那就是:Python的自定義異常處理

我有一個自定義的驗證異常,這需要請求和響應

class ValidationException(Exception): 
    message = "Caught Validation Exception" 

    def __init__(self, request, response): 
     self.details = { 
      "request": request, 
      "response": response 
     } 
     super(ValidationException, self).__init__(self.message, self.details) 

我有一個異常處理程序這將提高對一些條件的一個實例:

class handler: 
    if something: 
     raise ValidationException(request, response) 

處理程序被調用時,我們遇到的問題在後

class Poster: 
    def post(data): 
     if self.last_response.status_code not in self.valid_post_codes: 
      self.exception_handler.handleException(self.last_request, self.last_response) 

問題是,我提高了ValidationException,得到它在我的追蹤,但它似乎並沒有被抓到我想要的地方。

def testThis(self): 
    try: 
     self.poster.post(json.dumps({})) 
    except ValidationException: 
     print "got validation" 
    except Exception: 
     print "got exception" 

結果: 「有異常」

回溯

lib/service/pas/api/order.py line 24 in postOrder 
    return self.post() 
lib/service/base.py line 42 in post 
    self.exception_handler.handleException(self.last_request, self.last_response) 
lib/service/exception/handler.py line 14 in handleException 
    raise ValidationException(request, response) 
ValidationException: 

爲了什麼它的價值:

assertRaises(ValidationException, self.poster.post, json.dumps({})) 

只捕獲異常也是如此。有任何想法嗎? :\ 任何幫助是極大的讚賞!在此先感謝

回答

0

我無法給予代碼複製它,但有兩個可疑的地方需要考慮:

  1. 你似乎是混合舊式和新式的類。這可能會導致微妙的錯誤。嘗試class Handler(object):class Poster(object):,並在所有其他情況下,使類明確的子類爲object的新類。

  2. 你似乎有一個複雜的異常調用機制,與

    self.exception_handler.handleException(self.last_request, self.last_response) 
    

    爲什麼不乾脆:

    raise ValidationException(self.last_request, self.last_repsonse) 
    

    在那裏?至少作爲調試實驗,移除或短路您不確定或不能預防的模塊,功能和代碼。切入正題,看看你是否可以解決這個問題。至少,這可能會幫助您縮小問題所在。如果它在處理程序中,則可以選擇修復它,或者將其卡入。

+0

非常感謝您的幫助! – mikeyseay 2014-10-31 00:38:09

1

好吧好吧好吧...所以..

我的IDE前綴我的進口與進口Exceptions.ValidationException 「LIB」。

當我在其他地方拋出my.own.ValidationException時,它沒有被捕獲,因爲它不是相同的類型。剛剛發生了碰巧有另一個ValidationException我不知道...

這太神奇了,不!