If I try to commit a record to my database and it already exists then I want to use a try/except block to handle it:
from sqlalchemy.exc import IntegrityError
try:
session.commit()
except IntegrityError:
# do something else
However, I can't seem to catch the error. Here's a typical error that occurs on session.commit():
Exception has occurred: IntegrityError
(mysql.connector.errors.IntegrityError) 1062 (23000): Duplicate entry '88306-1' for key 'match_feat.idx_match_feat__composite'
I wondered if I was trying to catch the wrong error so I tried using:
from mysql.connector.errors import IntegrityError
But I get the same error message.
The answers to the question here focus on adding session.rollback() to the except: block however this doesn't help me (or the OP?) as I'm getting the error in the try: block and so the except: block isn't ever triggered.
passbut when put into an other transaction, the exception will be remembered by the parent transaction, and once you try to commit the parent session tx it will rollback telling you that you have an issue