【发布时间】:2014-08-22 17:21:27
【问题描述】:
尽我所能,我似乎无法正确捕捉到 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
更新:
我发现了一些似乎适合这里发生的事情,在会话刷新到数据库之前不会引发完整性错误,并且在执行 try/exceptblocks 之后:Trying to catch integrity error with SQLAlchemy
但是,在try 块中添加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)
【问题讨论】:
-
你是 100% 发生这种情况的吗?
-
您使用的是哪个数据库?
-
另外,将
IntegrityError更改为DatabaseError有帮助吗?谢谢。 -
@alecxe
DatabaseError似乎没有帮助,我正在使用 Postgres。 -
@MartinKonecny 是的,我很确定。印刷声明比比皆是。我在这里缺少一些东西,但是什么?也许在会话中处理事务的方式中,在会话刷新到数据库之前不会抛出 IntegrityError,如下所述:stackoverflow.com/questions/11313935/…
标签: python exception exception-handling error-handling sqlalchemy