14

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?

1
  • How / when are you committing your transaction? The IntegrityError will likely be raised when your transaction gets committed, not when calling the stored procedure. Commented Nov 25, 2014 at 20:26

4 Answers 4

19

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'>
Sign up to request clarification or add additional context in comments.

1 Comment

just to add since I had a similar problem. I couldnt catch it either. I had to import pymysql; except pymysql.IntegrityError;
4

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}

Comments

2

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

1 Comment

OP is asking about pymysql, not Django.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.