pythonsqlalchemyspyderexceptasyncpg

How to integrate except: raise with sqlalchemy's exceptions? SQLAlchemyError not working


I have the session rollback whenever I try to execute the statement in main.py. In db_commands.py I have the except: raise clause that should allow me to catch any errors that caused the rollback, e.g. IntegrityError, but the code raises no exceptions for some reason. I have read carefully the documentation on SQLAlchemy's core exceptions and the background on except: raise, as well as suitable suggested questions on stackoverflow including this but found no reason for this not to happen. The only reason that comes to my mind is to import all the exceptions first. If yes, how to integrate them properly with the except: raise clause? I use Spyder IDE if that may be the cause for any reason.

db_commands.py:

from sqlalchemy.exc import SQLAlchemyError

...

async def retrieve_data_from_db(query, my_async_session: AsyncSession):

""" Connects to the database and returns the results for a given query """

async with my_async_session.begin() as session:
    try:
        executed_query = await session.execute(query)
    except SQLAlchemyError:
        raise
    finally:
        await session.close()
    return executed_query

main.py:

query = select(UserBase).where(UserBase.telegram_id == telegram_id)
result = await retrieve_data_from_db(query, async_session_maker)

asyncpg==0.28.0
SQLAlchemy==2.0.19

Solution

  • For some reason, Spyder does not provide the background on the error. Making it

    except SQLAlchemyError as exc:
        print(exc)
        raise
    

    showed the error and now I am able to deal with it.