I want to handle a case where there’s a primary key or unique key conflict, a.k.a. a duplicate entry. For this I’m catching the IntegrityError, which catches the error just fine. The problem is, I can’t seem to find any simple error message or error code to check for. All I’m getting is the IntegrityError.message property which is a string that looks like this:
(IntegrityError) (1062, “Duplicate entry ‘foobar’ for key ‘name'”)
That’s not very helpful. Using that I’m going to have to start parsing error messages for their code and message. Calling dir on the exception shows only the following properties:
‘args’, ‘connection_invalidated’, ‘instance’, ‘message’, ‘orig’, ‘params’, ‘statement’
args is simply a single-item tuple with the aforementioned string inside it and params is the data I tried to insert. I can’t seem to find any way of determining that this actually is a duplicate key error without having to start parsing the error message using regex or something.
Can anyone shed some light on this issue?
I figured this out while writing the question by reading the documentation more carefully. I’m still going to post this though since it might be of help to someone.
In the documentation of the SQLAlchemy DBAPIError, from which the IntegrityError is subclassed, it explains that the exception is merely a wrapper for the underlying database API error and that the original error is saved as
origin the exception. Sure enough, callinge.orig.argsI get a nicely organized tuple: