简体   繁体   English

简化Python中的try-except块

[英]Simplify try-except blocks in Python

I have a number of modules. 我有很多模块。 They all have similar try-except blocks in each file, like this: 它们在每个文件中都有类似的try-except块,如下所示:

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

with ArgException (and other exceptions) being defined as: 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

Since every module uses similar code to catch exceptions, is there a way to put the exception catching into a shared file that is used by all modules? 由于每个模块都使用类似的代码来捕获异常,是否有办法将异常捕获放入所有模块都使用的共享文件中?

I would not do that, but you could create a function in a module like : 我不会这样做,但是您可以在类似以下的模块中创建一个函数:

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')

and then call try_exec(do_the_main_app_here) whenever you need to try catch your block of instructions, passing the parameters you need to have the correct context. 然后在需要尝试捕获指令块时传递try_exec(do_the_main_app_here) ,并传递需要具有正确上下文的参数。

The answer is Yes, you can create a module to do that. 答案是肯定的,您可以创建一个模块来做到这一点。

The easiest way would be to create a function accepting two parameters: another function with the code that you want to "try" and an "action" to be taken in case of exception. 最简单的方法是创建一个接受两个参数的函数:另一个函数是您要“尝试”的代码,以及在发生异常的情况下要执行的“操作”。

Then: 然后:

def myModuleFunction(tryThisCode, doThis):
    try:
        returnValue = tryThisCode()
        return returnValue
    except ArgException as e:
        if (doThis == "doThat"):
           ...
        else:
           ...

Then, after importing your new module, you can use your function like this: 然后,在导入新模块之后,您可以使用如下功能:

myModuleFunction(divideByZero, 'printMe')

Assuming you have a function called divideByZero(); 假设您有一个名为divideByZero()的函数;

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM