catching SQLAlchemy exceptions

PythonSqlalchemyException

Python Problem Overview


What is the upper level exception that I can catch SQLAlechmy exceptions with ?

>>> from sqlalchemy import exc
>>> dir(exc)
['ArgumentError', 'CircularDependencyError', 'CompileError', 'ConcurrentModificationError', 'DBAPIError', 'DataError', 'DatabaseError', 'DisconnectionError', 'FlushError', 'IdentifierError', 'IntegrityError', 'InterfaceError', 'InternalError', 'InvalidRequestError', 'NoReferenceError', 'NoReferencedColumnError', 'NoReferencedTableError', 'NoSuchColumnError', 'NoSuchTableError', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'SADeprecationWarning', 'SAPendingDeprecationWarning', 'SAWarning', 'SQLAlchemyError', 'SQLError', 'TimeoutError', 'UnboundExecutionError', 'UnmappedColumnError', '__builtins__', '__doc__', '__file__', '__name__', '__package__']
>>> 

Python Solutions


Solution 1 - Python

To catch any exception SQLAlchemy throws:

from sqlalchemy import exc
db.add(user)
try:
  db.commit()
except exc.SQLAlchemyError:
  pass # do something intelligent here

See help(sqlalchemy.exc) and help(sqlalchemy.orm.exc) for a list of possible exceptions that sqlalchemy can raise.

Solution 2 - Python

From the source:

> The base exception class is > SQLAlchemyError.

Solution 3 - Python

Depending on your version of SQLAlchemy (e.g. 1.0.4), you may need to do a little more to get to the base-SQLAlchemyError class:

from flask.ext.sqlalchemy import exc
exceptions = exc.sa_exc

try:
    my_admin = user_models.User('space cadet', active=True)
    db.session.add(my_admin)
    db.session.commit()
except exceptions.SQLAlchemyError:
    sys.exit("Encountered general SQLAlchemyError.  Call an adult!")

this is because sqlalchemy.orm.exc now has the stanza:

"""SQLAlchemy ORM exceptions."""
from .. import exc as sa_exc, util

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkhelllView Question on Stackoverflow
Solution 1 - PythonbbrameView Answer on Stackoverflow
Solution 2 - PythonstephanView Answer on Stackoverflow
Solution 3 - Pythonuser559633View Answer on Stackoverflow