kmansoor
kmansoor

Reputation: 4345

Figuring out 'Which Constraint' was violated from SQLException

My code can encounter a 'Constraint Violation Exception' (CVE) for a number of different constraints. In order to display a meaningful message to the user and to take specific action I am parsing the String returned by getMessage(). It works but is ugly and surely not easy to maintain.

I'm wondering if there is a better way? This must be a pretty common scenario; is there a pattern or best practice I could follow?

Thank you.

Upvotes: 5

Views: 601

Answers (1)

coolest_head
coolest_head

Reputation: 1436

AFAIK, since you are interesting in which specific constraint failed, whatever you are doing is the only way to go.

I am not sure which database you are talking about, but you might try.. SQLException.getErrorCode() and SQLException.getSQLState(). These would give you more information depending on the db vendor.

For example, in Oracle, SQLException.getErrorCode() would just tell you a constraint is violated, not necessarily which constraint.

Upvotes: 2

Related Questions