Let's say I executed an SQL statement from a C# application that caused an SqlException with the following error message to be thrown:
Violation of UNIQUE KEY constraint 'MyUniqueConstraint'. Cannot insert duplicate key in object 'MyTable'. The duplicate key value is (MyValue).
I understand that the entire string comes from the database. I would like to extract the relevant parts from the message - similar to this question, but I want to actually extract data such as MyUniqueConstraint
, MyTable
and MyValue
, not just the SQL error number.
Actually parsing the message is not an option as it is error-prone: you have to do it for every possible error, and if the error text changes from one version of SQL server to another, there would be serious problems.
Is it possible to reasonably obtain such structured information from the application when a database-level error occurs (ideally from the exception)?
Not long ago I faced a similar problem, and I found out that even filtering SqlExceptions based on their numbers is problematic.
Other than that, I haven't yet encountered a solution that could get data details from SqlException. That is, other than parsing the message. One of the problems here will be that text of server message is different for different languages and server versions
Actually I recall there is a system table/view in the mssql master database that contains all error messages for different languages. You can try parsing the messages based on that, but some SqlExceptions aren't even from the server side of things...
I want to say at least one remotely helpful thing here, so:
In the namespace System.Data there is DBConcurrencyException which seems to be usefull to an extent (meaning: in a single case that is not entirely related to this question). It has Row property (row that caused the exception to be thrown, you can use it to get the table name and the data).