cannot catch MySQL IntegrityError in Python
The problem was I was catching the incorrect exception.
It turned out the error raised is actually of type pymysql.err.IntegrityError
and not sqlalchemy.exc.IntegrityError
as I assumed.
I found out the exception type by doing:
import sys
try:
cursor = connection.cursor()
cursor.callproc('my_stored_proc', [arguments])
except:
print "Unexpected error:", sys.exc_info()[0]
And I saw this printout:
Unexpected error: <class 'pymysql.err.IntegrityError'>
In my case and may be this helps you too, I was using MYSQL as database so to catch exceptions I need to import exceptions
from django.db.utils import IntegrityError
Then you can try and catch it like this
try:
#your code
except IntegrityError:
#your code when integrity error comes
In my case, and also yours, you'd use the sqlalchemy object:
try:
cursor = connection.cursor()
cursor.callproc('my_stored_proc', [arguments])
except sqlalchemy.exc.IntegrityError as e:
print("Error: {}".format(e))
return {"message": e.message}