我正在我的 python 代码中自定义异常。我已经将异常类继承给其他类,现在将一些自定义错误定义为从我的自定义异常类派生的类,如下所示:
class DataCollectorError(Exception): pass
class ParamNullError(DataCollectorError) : pass
class ParamInvalidTypeError(DataCollectorError) : pass
我在我的 python 函数中引发了这些异常,例如:
def READ_METER_DATA (regIndex, numRegisters, slaveUnit):
try:
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"
和记录错误如:
except DataCollectorError as d:
lgr.error('DataCollector Error(READ_METER_DATA): '+d.args[0])
print 'DataCollector Error:(READ_METER_DATA)', d.args[0]
except:
lgr.error('Unexpected Error: ', sys.exc_info())
print 'Unexpected Error: ', sys.exc_info()
pass
但这违背了单元测试脚本的目的,因为它不知道是否引发了异常,因为它在我的单元测试脚本知道之前被我的 catch block 捕获了。所以我想在基类本身中记录这些错误 -
Class ParamNullError(DataCollectorError):
<----here----------->
pass
谁能告诉我如何在引发异常时获取传递的字符串?
最佳答案
只需使用 __init__
和 __str__
方法扩展您的错误类。
例子:
class DataCollectorError(Exception):
def __init__(self, msg=''):
self.msg = msg
log(msg) # use your logging things here
def __str__(self):
return self.msg
使用 msg=''
因为这样您就不需要总是指定一条消息。
关于python - 在 python 中自定义异常?在自定义异常类中写入日志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16788884/