python - 无法捕获 SQLAlchemy IntegrityError

标签 python exception exception-handling error-handling sqlalchemy

尽我所能,我似乎无法正确捕捉到 sqlalchemy IntegrityError:

from sqlalchemy import exc

try:
    insert_record()
except exc.IntegrityError, exc:
    print exc # this is never called
    handle_elegantly() # this is never called

正如人们所期望的那样:

IntegrityError: (IntegrityError) insert or update on table "my_table" 
                violates foreign key constraint "my_table_some_column_fkey"

我已尝试明确:

from sqlalchemy.exc import IntegrityError

更新:

我发现一些似乎适合这里发生的事情,在 session 刷新到数据库之前不会引发完整性错误,并且在 try/except 之后 block 已被执行:Trying to catch integrity error with SQLAlchemy

但是,在 try block 中添加 session.flush() 会产生 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)

最佳答案

我的 Flask 应用程序也有同样的需求,我按如下方式处理它并且它可以工作:

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()

关于python - 无法捕获 SQLAlchemy IntegrityError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24522290/

相关文章:

spring - Spring MVC没有请求映射时如何处理异常?

c++ - 如何使用 std::nested_exception 和 friend ?

spring-mvc - Spring MVC @ExceptionHandler 链接

python - 为什么复制的字典指向同一个目录而列表却没有?

python - 保留满足两个或多个条件的 numpy 数组的值

python-3.x - Linux 上 Python3.6 回溯中的 ModuleNotFoundError

Java catch 被忽略

python - 如何指定 Tkinter 窗口打开的位置?

python - 带有 WKT 列的 DataFrame 到 GeoPandas 几何

python - 如何改进 python/django 中的异常处理