简体   繁体   中英

Simplify try-except blocks in Python

I have a number of modules. They all have similar try-except blocks in each file, like this:

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:

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.

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();

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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