无法在Python中捕获MySQL IntegrityError

Jan*_*ana 5 python mysql stored-procedures exception-handling sqlalchemy

我使用Python/Bottle/SqlAlchemy/MySQL作为Web服务.

我试图通过调用存储过程来捕获IntegrityError,但我无法做到这一点.

用这个

cursor = connection.cursor()
cursor.callproc('my_stored_proc', [arguments])
Run Code Online (Sandbox Code Playgroud)

产生与...相同的结果

try:
    cursor = connection.cursor()
    cursor.callproc('my_stored_proc', [arguments])
except IntegrityError as e:
    print("Error: {}".format(e))
    return {"message": e.message}
Run Code Online (Sandbox Code Playgroud)

在这两种情况下我都会遇到IntegrityError异常.为什么在后一种情况下没有发现异常?

Jan*_*ana 10

问题是我抓到了不正确的异常.

事实证明,引发的错误实际上是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]
Run Code Online (Sandbox Code Playgroud)

我看到了这个打印输出:

Unexpected error: <class 'pymysql.err.IntegrityError'>