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:
from flask import Flask from flask_sqlalchemy import SQLAlchemy from sqlalchemy import exc db = SQLAlchemy(Flask(__name__)) try: db.session.add(resource) return db.session.commit() except exc.IntegrityError: db.session.rollback()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With