Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 316
Jana Avatar asked Nov 25 '14 20:11

Jana


1 Answers

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
like image 93
Shaz Avatar answered Sep 25 '22 13:09

Shaz