Python error handlers

I have difficulty finding a โ€œpythonicโ€ way to do this: I need to catch different blocks of code with the same try-except pattern. The catch blocks are different from each other. I am currently repeating the same try-except pattern at multiple points in the code with a long list of exceptions.

try:
    block to catch
except E1, e:
    log and do something
except E2, e:
    log and do something
...
except Exception, e:
    log and do something

There is a good way to solve this problem using the with statement and the context manager decoder:

from contextlib import contextmanager

@contextmanager
def error_handler():
    try:
        yield
    except E1, e:
        log and do something
    ...
    except Exception, e:
        log and do something


...
with error_handler():
    block to catch
...

But what happens if I need to know if there was an exception in the block? those. Is there any alternative to doing something like the previous one with a block for try-except-else?

Usage example:

for var in vars:
    try:
        block to catch
    except E1, e:
        log and do something
        # continue to the next loop iteration
    except E2, e:
        log and do something
        # continue to the next loop iteration
    ...
    except Exception, e:
        log and do something
        # continue to the next loop iteration
    else:
        do something else

Can I do something similar in pythonic to avoid repeating the same try-except pattern over and over again?

+4
3

, , , , , , .

, , / - , , "Pythonic" , , .

from contextlib import contextmanager

@contextmanager
def error_handler():
    error = True
    try:
        class Internal:
            def caughtError(self): return error
        yield Internal()
    except Exception as e:
        print("Logging#1")
    except BaseException as e:
        print("Logging#2")
    else:
        error = False

with error_handler() as e:
    print("here")
#    raise Exception("hopp")

print(e.caughtError())         # True if an error was logged, False otherwise
+1

.

def error_handler(exception):
    if isinstance(exception, E1):
        log and do something
    elif isinstance(exception, E2):
    ...
    else:
        log and do something

try:
    block to catch
except Exception, e:
    error_handler(e)
else:
    do something else
+1

, , , , :

def foo():
    try:
        something = xxx
    except ValueError as e:
        logging.warn("oh noes %s", e)
        return 42
    except IndexError as e:
        logging.warn("on no, not again %s", e)
        return 43

    go.on(something=something)

:

def foo():
    try:
        something = xxx
    except Exception:
        logging.exception("oh noes")
        return

    go.on(something=something)

, , :

def foo():
    go.on(something=xxx)

.

Crash Early

0
source

Source: https://habr.com/ru/post/1538835/


All Articles