Try as I might, I can't seem to catch the sqlalchemy IntegrityError correctly:
from sqlalchemy import exc
try:
insert_record()
except exc.IntegrityError, exc:
print exc # this is never called
handle_elegantly() # this is never called
As what one might expect:
IntegrityError: (IntegrityError) insert or update on table "my_table"
violates foreign key constraint "my_table_some_column_fkey"
I've tried to explicitly:
from sqlalchemy.exc import IntegrityError
UPDATE:
I found something that seems to fit what's happening here, where Integrity Error isn't thrown until the session is flushed to the db, and after the try
/except
blocks have been executed: Trying to catch integrity error with SQLAlchemy
However, adding session.flush()
in the try
block yields an InvalidRequestError
:
ERROR:root:This Session's transaction has been rolled back due to a previous
exception during flush. To begin a new transaction with this Session,
first issue Session.rollback().
Original exception was: (IntegrityError)
I have the same need in my Flask application, I handle it like below and it works:
As soon as the
IntegrityError
is raised, regardless of whether or not you've caught the error, the session you were working in is invalidated. As the second error message is instructing you,To begin a new transaction with this Session, first issue Session.rollback().
, to continue using the session you'll need to issue asession.rollback()
I cannot say for sure, but I am guessing you or your web framework is attempting to continue using the session which raised the IntegrityError in some way. I recommend you issue a
session.rollback()
either after you catch the exception or in yourhandle_elegantly
function.If you run the below you'll see what I mean: