我正在使用Python/Bottle/SqlAlchemy/MySQL作为web服务。
我正在尝试捕获通过调用存储过程引发的IntegrityError,但我无法这样做。
使用这个
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异常。为什么在后一种情况下没有捕获到异常?
发布于 2014-11-26 04:39:54
问题是我捕捉到了不正确的异常。
事实证明,引发的错误实际上是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]
我看到了这个打印输出:
Unexpected error: <class 'pymysql.err.IntegrityError'>
发布于 2020-03-13 00:14:23
在我的示例中,也是在您的示例中,您将使用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}
发布于 2020-06-16 12:07:58
在我的情况下,这可能对您也有帮助,我使用MYSQL作为数据库,所以为了捕获异常,我需要导入异常
from django.db.utils import IntegrityError
然后你可以试着像这样捕捉它
try:
#your code
except IntegrityError:
#your code when integrity error comes
https://stackoverflow.com/questions/27135779
复制相似问题