在python中自定义异常?在自定义异常类中写入日志?

Ind*_*ngh 3 python inheritance exception-handling exception custom-exceptions

我正在我的 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):
    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"
Run Code Online (Sandbox Code Playgroud)

并记录错误,如:

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
Run Code Online (Sandbox Code Playgroud)

但这违背了单元测试脚本的目的,因为它不会在我的单元测试脚本知道异常之前是否被我的 catch 块捕获。所以我想在基类本身中记录这些错误 -

Class ParamNullError(DataCollectorError):
    <----here----------->
    pass 
Run Code Online (Sandbox Code Playgroud)

谁能告诉我如何获取在引发异常时传递的字符串?

Tob*_*arg 6

只需使用 an__init__和 an__str__方法扩展您的错误类。

例子:

class DataCollectorError(Exception):
    def __init__(self, msg=''):
        self.msg = msg
        log(msg)  # use your logging things here

    def __str__(self):
        return self.msg
Run Code Online (Sandbox Code Playgroud)

使用msg=''因为这样您就不需要总是指定消息。