﻿ 如何在装饰器中捕获相同类型的多个异常 - 代码日志

#### 如何在装饰器中捕获相同类型的多个异常

•输入将作为numGen函数给出.此numGen函数将输入添加到随机数.在我的例子中,我正在检查10个不同的随机数.
•注意输入也将随着随机数生成的范围而变化

**：编辑异常类

``````from random import randint
class RND_ERROR(Exception):
def __init__(self, ErrNum, *arg, **kwargs):
self.RND_ERR_NR = int(ErrNum)
self.RND_ERR_MSG = ""
if self.RND_ERR_NR == 0x00000000:
self.RND_ERR_MSG = "NO ERROR"
elif self.RND_ERR_NR == 0x00000001:
self.RND_ERR_MSG = "RANDOM NUMBER IS ONE"
elif self.RND_ERR_NR == 0x00000002:
self.RND_ERR_MSG = "RANDOM NUMBER IS TWO"
elif self.RND_ERR_NR == 0x00000003:
self.RND_ERR_MSG = "RANDOM NUMBER IS THREE"
else:
self.RND_ERR_MSG = "RANDOM NUMBER GREATER THAN THREE"
def __str__(self):
return "RND ERROR (0x%08X): %s" % (self.RND_ERR_NR,self.RND_ERR_MSG)

def __repr__(self):
return self.__str__()

def handleError(func):
errors =[]
def wrapper(arg1):
try:
result = func(arg1)
except MyException as e:
print errors.append(e)
return wrapper

def findError(func):
def wrapper(arg1):
result = func(arg1)
print result
for k, v in result.iteritems():
error_nr = v % 2
if error_nr ==0:
pass
elif error_nr > 0:
raise RND_ERROR(errornum) #edited lines
return wrapper

@handleError
@findError
def numGen(input):
from random import randint
result= {}
errors = []
for i in range(9):
j = (randint(0,4))
result[i] = input + j
result.update()    # This line does nothing...
return result
if __name__ == '__main__':
numGen(4)
``````

>我无法在try块中迭代字典,所以我无法捕获特定的错误.
>我想检查每个输入是否发生错误以及是否发生任何错误引发异常并存储哪个输入的信息

– 针对不同的输入提高异常.捕获异常,并存储发生异常的输入值以及异常类型(比如说).
>如何通过创建聚合异常来聚合异常,例如MyExceptionsCollection,它将保存数组并提升它而不是打印.
>如何重新确定已发生的确切异常或所有异常

``````class MyException(Exception):pass

def handleError(func):
errors =[]
def wrapper(arg1):
result = func(arg1)

for err in findError(result):
errors.append(err)

print errors
return result

return wrapper

def findError(result):
print result
for k, v in result.iteritems():
error_nr = v % 2
if error_nr ==0:
pass
elif error_nr > 0:
yield MyException

@handleError
def numGen(input):
from random import randint
result= {}
errors = []
for i in range(9):
j = (randint(0,4))
result[i] = input + j
return result

if __name__ == '__main__':
numGen(4)
``````