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)