代码之家  ›  专栏  ›  技术社区  ›  khelll

捕获SQLAlchemy异常

  •  33
  • khelll  · 技术社区  · 15 年前

    我可以用什么来捕获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 回复  |  直到 8 年前
        1
  •  35
  •   stephan    10 年前

    the source :

    基本异常类是 SQLAlchemyError .

        2
  •  43
  •   bbrame    8 年前

    要捕获任何异常,请执行以下操作:

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

    有关SQLAlchemy可能引发的异常列表,请参阅帮助(sqlAlchemy.exc)和帮助(sqlAlchemy.orm.exc)。

        3
  •  2
  •   user559633    9 年前

    根据您的sqlacalchemy版本(例如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