Cannot catch MySQL IntegrityError in Python

I am using Python / Bottle / SqlAlchemy / MySQL for a web service.

I am trying to catch an IntegrityError caused by a call to a stored procedure, but I cannot do this.

Using this

cursor = connection.cursor() cursor.callproc('my_stored_proc', [arguments]) 

gives the same result as

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

I get an IntegrityError exception in both cases. Why did the exception not fall into the latter case?

+5
source share
1 answer

The problem was that I chose the wrong exception.

It turned out that the error that occurred actually belongs to the type pymysql.err.IntegrityError, and not sqlalchemy.exc.IntegrityError, as I assumed.

I discovered the type of exception 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 listing:

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

+10
source

Source: https://habr.com/ru/post/1207694/


All Articles