Jana
Jana

Reputation: 5704

cannot catch MySQL IntegrityError in Python

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

I am trying to catch an IntegrityError raised by calling a stored procedure but I am unable to do that.

Using this

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

yields 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 is the exception not caught in the latter case?

Upvotes: 14

Views: 21960

Answers (4)

Dede95
Dede95

Reputation: 41

With pymysql I use:

import pymysql
# some code

try:
   #Your code
except pymysql.err.IntegrityError:
   # Your exception code
except Exception as e:
   # Raise all other exceptions. 
   raise e

Upvotes: 0

Jana
Jana

Reputation: 5704

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'>

Upvotes: 19

Shaz
Shaz

Reputation: 425

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

Upvotes: 2

Skulas
Skulas

Reputation: 507

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}

Upvotes: 4

Related Questions