无法在Python中捕获MySQL IntegrityError
我正在使用Python/瓶/SqlAlchemy/MySQL作为web服务 我试图捕获通过调用存储过程引发的IntegrityError,但我无法做到这一点 用这个无法在Python中捕获MySQL IntegrityError,python,mysql,stored-procedures,exception-handling,sqlalchemy,Python,Mysql,Stored Procedures,Exception Handling,Sqlalchemy,我正在使用Python/瓶/SqlAlchemy/MySQL作为web服务 我试图捕获通过调用存储过程引发的IntegrityError,但我无法做到这一点 用这个 cursor = connection.cursor() cursor.callproc('my_stored_proc', [arguments]) 产生的结果与 try: cursor = connection.cursor() cursor.callproc('my_stored_proc', [argume
cursor = connection.cursor()
cursor.callproc('my_stored_proc', [arguments])
产生的结果与
try:
cursor = connection.cursor()
cursor.callproc('my_stored_proc', [arguments])
except IntegrityError as e:
print("Error: {}".format(e))
return {"message": e.message}
在这两种情况下,我都得到IntegrityError异常。为什么在后一种情况下没有捕获异常?问题是我捕获的异常不正确 事实证明,引发的错误实际上是pymysql.err.IntegrityError类型,而不是我假设的sqlalchemy.exc.IntegrityError类型 我通过执行以下操作找到了异常类型:
import sys
try:
cursor = connection.cursor()
cursor.callproc('my_stored_proc', [arguments])
except:
print "Unexpected error:", sys.exc_info()[0]
我看到了这个打印件:
意外错误:
在我和你的例子中,你应该使用sqlalchemy对象:
try:
cursor = connection.cursor()
cursor.callproc('my_stored_proc', [arguments])
except sqlalchemy.exc.IntegrityError as e:
print("Error: {}".format(e))
return {"message": e.message}
在我的例子中,这可能也对您有所帮助,我使用MYSQL作为数据库,以便捕获异常,我需要导入异常
from django.db.utils import IntegrityError
然后你可以试着像这样抓住它
try:
#your code
except IntegrityError:
#your code when integrity error comes
您如何/何时提交交易?
IntegrityError
可能会在事务提交时引发,而不是在调用存储过程时引发。只是补充一下,因为我遇到了类似的问题。我也抓不到它。我必须导入pymysql;除了pymysql.IntegrityError;