Ind*_*ngh 2 python inheritance logging exception-handling
我正在我的 python 代码中自定义异常。我已经将异常类继承到其他类,现在将一些自定义错误定义为从我的自定义异常类派生的类,如下所示:
class DataCollectorError(Exception): pass
class ParamNullError(DataCollectorError) : pass
class ParamInvalidTypeError(DataCollectorError) : pass
Run Code Online (Sandbox Code Playgroud)
我在我的 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"
Run Code Online (Sandbox Code Playgroud)
现在我想使用 logger 将错误消息记录到日志文件中,但不知道在哪里做。
DataCollectorError)ParamNullError等的个别错误类别中。但是后来我不知道在哪里以及如何获取该错误消息以记录它们。
只需使用标准日志模块;它会用开箱即用的异常消息记录您的异常。
当您的应用程序捕获异常时,使用该logging.exception()函数记录它;异常会自动添加到日志条目中:
log = logging.getLogger('some-identifier')
try:
#
except DataCollectorError:
log.exception('An error occurred')
Run Code Online (Sandbox Code Playgroud)
.args默认情况下,异常有一个元组参数,该元组中的第一个值是您的消息。
关于你的代码的一些风格反馈:
不要测试== False. 相反,使用not:
if not isinstance(regIndex, int):
Run Code Online (Sandbox Code Playgroud)引发您的异常实例:
raise ParamNullError("register index is null")
Run Code Online (Sandbox Code Playgroud)
而不是raise class, message样式,以便更容易地迁移到 Python 3。
| 归档时间: |
|
| 查看次数: |
1002 次 |
| 最近记录: |