In C# Is there a way of getting a finer granularity with SQL exceptions?
I'm aware that an aweful lot can go wrong but I want to deal with certain cases differently and parsing the Error message doesn't seem to be very elegant.
Also Are the error messages created by the framework or are they db specific?
For example If i have a primary key violation on INSERT is the error message going to always be:
Violation of PRIMARY KEY constraint 'PK_tblProduct'. Cannot insert duplicate key in object 'dbo.tblProduct'.
or is that SQLServer specific.
Update
I looks like I'm after the error number, any idea where I can get the various error numbers?
best I can do with a quick google is: 18456: Logon Failed 18488: Password Expired
If you are catching a SqlException
, you should have access to .Number
, which gives you the SQL error number; this is probably your best approach... (you can get the same from the InfoMessage
event as well for non-fatal errors).
Of course, this won't distinguish between tables - you could argue that if you need this level of granularity, you should check first (in a serializable isolation level, ideally with UPDLOCK), raising your own error if there is conflicting data.