catching SQLAlchemy exceptions

前端 未结 3 585
长发绾君心
长发绾君心 2021-01-31 14:21

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

>>> from sqlalchemy import exc
>>> dir(exc)
[\'ArgumentError\',         


        
相关标签:
3条回答
  • 2021-01-31 14:28

    From the source:

    The base exception class is SQLAlchemyError.

    0 讨论(0)
  • 2021-01-31 14:30

    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.

    0 讨论(0)
  • 2021-01-31 14:53

    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
    
    0 讨论(0)
提交回复
热议问题