簡體   English   中英

在python中自定義異常。 如何記錄錯誤?

[英]Customizing exceptions in python. How to log errors?

我正在自定義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. 我應該通過將功能代碼放入try catch中來做到這一點,但是我將如何獲取這些錯誤消息
  2. 我應該在我創建的自定義錯誤類( DataCollectorError )中執行此操作DataCollectorError
  3. 或類似ParamNullError等的單個錯誤類中。

但是然后我不知道在哪里以及如何獲取該錯誤消息來記錄它們。

只需使用標准的日志模塊 ; 它會立即記錄您的異常以及異常消息。

當您的應用程序捕獲到異常時,請使用logging.exception()函數對其進行記錄; 例外會自動添加到日志條目:

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樣式),以便更輕松地遷移到Python 3。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM