2013-05-14 62 views
2

我在我的python代碼中自定義異常。我繼承了異常類中其他現在定義爲類從我的自定義異常類派生一些像這樣的自定義錯誤:在python中自定義異常。如何記錄錯誤?

class DataCollectorError(Exception): pass 
class ParamNullError(DataCollectorError) : pass 
class ParamInvalidTypeError(DataCollectorError) : pass 

我養我的Python函數這些異常,如:

def READ_METER_DATA (regIndex, numRegisters, slaveUnit): 
    if not regIndex: 
     raise ParamNullError, "register index is null" 

    if not numRegisters: 
     raise ParamNullError, "number of registers should not be null" 

    if not slaveUnit: 
     raise ParamNullError, "Meter Id should not be null" 

    if(isinstance(regIndex, int) == False): 
     raise ParamInvalidTypeError, "register index passed is not int" 

    if(isinstance(numRegisters, int) == False): 
     raise ParamInvalidTypeError, "number of registers passed is not int" 

現在我想使用記錄器將錯誤消息記錄到日誌文件中,但不知道在哪裏做。

  1. 我應該做它通過把該函數的代碼在嘗試捕捉,但再怎麼會我會得到這些錯誤消息
  2. 我應該做的自定義錯誤類中,我創建(DataCollectorError
  3. 或個別錯誤類,如ParamNullError

但是當時我不知道在哪裏以及如何得到該錯誤消息記錄它們。

+0

'如果移動到Python 3。不是isinstance(regIndex,int):'是更好的風格,並且總是避免與布爾值進行比較,除非這真是你的意思。而且,這些特定的示例檢查看起來更好地被'assert'服務。 – Will 2013-05-14 09:41:55

回答

4

只需使用標準logging module;它會將您的例外開箱即用的例外信息記錄下來。

當您的應用程序發現異常時,請使用logging.exception() function進行記錄;異常被自動添加到日誌條目:

log = logging.getLogger('some-identifier') 

try: 
    # 
except DataCollectorError: 
    log.exception('An error occurred') 

例外都默認一個.args元組參數,並在元組中的第一個值是你的消息。

您的代碼風格的一些反饋:

  • 不要測試== False。相反,使用not

    if not isinstance(regIndex, int): 
    
  • 你的異常籌集實例:

    raise ParamNullError("register index is null") 
    

    而非raise class, message風格,使其更容易

+0

我想要那個引發異常的消息。我將如何得到它?我也想問,提出這些異常之後,這段代碼將轉到下一行或函數將退出? – 2013-05-14 10:03:54

+0

@InderpalSingh:引發異常意味着正常的代碼流被中斷。在捕捉並處理異常之前,函數立即退出*並且不執行下一行。 – 2013-05-14 10:07:53

+0

@InderpalSingh:你想對異常在[Python的教程]如何工作讀了(http://docs.python.org/2/tutorial/errors.html)吧? – 2013-05-14 10:09:04