SQLAlchemy error handling - how is it done?

Viewed 17072

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?

2 Answers
Related