Amit Pathak
Amit Pathak

Reputation: 1367

Is there a way to catch return statements from contextmanager in python?

I am trying to catch an SQLAlchemy operation result but am unsure if I can do it. Following is the code -

@contextmanager
def transaction_scope(session, close_at_exit=False):
    try:
        yield session
        session.commit()
        return True
    except Exception:
        session.rollback()
        return False
    finally:
        if close_at_exit:
            session.close()

with Session() as session:
    with transaction_scope(session):
        session.add(row)
        # Catch if the above insert (add) operation is successful or not

I am inserting a record into the database. I want to get the boolean response from the transaction_scope() if my insert operation is successful or not.

Upvotes: 2

Views: 91

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

You can always catch, respond to, and rethrow an exception.

with Session() as session:
    with transaction_scope(session):
        try:
            session.add(row)
        except Exception as exc:
            # Oh no! It failed! Do something here...
            raise

Note that the raise keyword, without an exception, can only be used in an except block and re-raises the current exception with its original stack trace intact. So we can respond to the exception and then re-raise it to allow the transaction_scope to roll back the transaction as it's supposed to.

Upvotes: 1

Related Questions