4

我正在我的 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 块捕获是否引发异常。所以我想在基类本身中记录这些错误-

Class ParamNullError(DataCollectorError):
    <----here----------->
    pass 

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

4

2 回答 2

7

__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='',因为这样您就不需要总是指定消息。

于 2013-05-28T10:00:02.287 回答
1

不。

分解出您需要进行单元测试的调用,并将您的异常处理程序移出:

try:
     testableFunctionCall()
except:
     lgr.exception('Unexpected Error')

和测试testableFunctionCall()

或者,使用该testfixtures来测试日志记录本身:

from testfixtures import LogCapture
with LogCapture() as l:
    callFunctionUnderTest()

l.check(
     ('packagename', 'ERROR', 'DataCollector Error(READ_METER_DATA): foobar'),
)
于 2013-05-28T10:01:43.183 回答