尽管我努力尝试,但似乎无法正确捕获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
/except
块已被执行后,才会抛出完整性错误: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)
"ERROR:root:This Session's...
。在我看来,print exc
生成了那个消息? - Martin Konecny