我在我的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"
現在我想使用記錄器將錯誤消息記錄到日誌文件中,但不知道在哪裏做。
- 我應該做它通過把該函數的代碼在嘗試捕捉,但再怎麼會我會得到這些錯誤消息
- 我應該做的自定義錯誤類中,我創建(
DataCollectorError
) - 或個別錯誤類,如
ParamNullError
等
但是當時我不知道在哪裏以及如何得到該錯誤消息記錄它們。
'如果移動到Python 3。不是isinstance(regIndex,int):'是更好的風格,並且總是避免與布爾值進行比較,除非這真是你的意思。而且,這些特定的示例檢查看起來更好地被'assert'服務。 – Will 2013-05-14 09:41:55