我在我的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