捕获SQLAlchemy异常

时间:2010-02-03 16:53:00

标签: python sqlalchemy exception

我可以捕获SQLAlechmy异常的上层异常是什么?

>>> 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__']
>>> 

3 个答案:

答案 0 :(得分:47)

捕获SQLAlchemy抛出的任何异常:

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

请参阅help(sqlalchemy.exc)和help(sqlalchemy.orm.exc)以获取sqlalchemy可能引发的可能异常列表。

答案 1 :(得分:36)

来自the source

  

基本异常类是   SQLAlchemyError

答案 2 :(得分:2)

根据您的SQLAlchemy版本(例如1.0.4),您可能需要多做一些才能到达基础 - SQLAlchemyError类:

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!")

这是因为sqlalchemy.orm.exc现在有节:

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