Sherwin
Sherwin

Reputation: 65

How to get the Constraint Code that is shown in a Message property of thrown SqlException

Suppose I have a Exception Message like

Violation of UNIQUE KEY constraint 'UC_FileTypeName'. Cannot insert duplicate key in object 'dbo.FileUpload'.  

Is there any class method or way to get the constraint named 'UC_FileTypeName' ? Since I was going to look up this constraint name in our database and show the descriptive message.

I was thinking of reading the the whole string and get the string that starts with 'UC' and ends with '. But I know there are other constraint error like 'FK_' etc, so its not a good idea.

Upvotes: 0

Views: 281

Answers (1)

John Saunders
John Saunders

Reputation: 161783

Don't ever, under any circumstances, depend on parsing the Message property of an exception. In fact, don't ever depend on parsing any human-readable output.

It's not intended to be parsed. It's intended to be read by a human. Such messages can and do change based on changes in the current culture, and can change from release to release as grammar errors are corrected.

Even if you had the equivalent "friendly" message, do you really think your users can understand something like, "Sorry, you can't enter another row with the same A, B, and C columns as an existing row"?

Your best bet would be to validate your data first, and not even attempt to enter a row that would violate any constraints.

Upvotes: 1

Related Questions