我有很多模块。它们在每个文件中都有类似的try-除了块,如下所示:
from shared.Exceptions import ArgException # and others, as needed
try:
do_the_main_app_here()
except ArgException as e:
Response.result = {
'status': 'error',
'message': str(e)
}
Response.exitcode('USAGE')
# more blocks like the above将ArgException (和其他异常)定义为:
from abc import ABCMeta, abstractmethod
class ETrait(Exception):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class ArgException(ETrait): pass由于每个模块都使用类似的代码来捕获异常,有没有一种方法可以将异常捕获放到所有模块都使用的共享文件中?
发布于 2015-12-04 18:40:55
我不会这么做,但您可以在模块中创建一个函数,如下所示:
from shared.Exceptions import ArgException # and others, as needed
def try_exec(execution_function)
try:
execution_function()
except ArgException as e:
Response.result = {
'status': 'error',
'message': str(e)
}
Response.exitcode('USAGE')然后在需要捕获指令块时调用try_exec(do_the_main_app_here),传递具有正确上下文所需的参数。
发布于 2015-12-04 18:44:28
答案是肯定的,你可以创建一个模块来做这件事。
最简单的方法是创建一个接受两个参数的函数:另一个包含您想要“尝试”的代码的函数,以及在出现异常时要采取的“操作”。
然后:
def myModuleFunction(tryThisCode, doThis):
try:
returnValue = tryThisCode()
return returnValue
except ArgException as e:
if (doThis == "doThat"):
...
else:
...然后,在导入新模块后,您可以像这样使用函数:
myModuleFunction(divideByZero, 'printMe')假设您有一个名为divideByZero()的函数;
我希望这能帮到你。
https://stackoverflow.com/questions/34086254
复制相似问题