Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling database exceptions in .net

When we can catch an exception like: Violation of UNIQUE KEY constraint 'IX_Product'. Cannot insert duplicate key in object 'Product'. (2627).
The challenge is how to dechiper the Index Name IX_Product as a Member (i.e. I don't want to substring out the message). There could be more than one unique constraint on a table and we would need to know which one to give more detailed information to the user. It would be preferable to catch it as DbException so it isn't SQL Server specific. Is there a way to get the affected index from the exception without having to parse the string?

The only solution I have came up with but I have not tested would to use a stored procedure and trap the error in there and returned the more detailed message from the stored procedure. But I believe this would still have issues.


2 Answers

You'll have to either:

  1. code your client component to recognize the constraint names that each insert/update statement might throw exceptions for,
  2. rename all your constraints so that they are "decipherable" in the way you want to use them in client code, or...
  3. check all the contraints in a stored proc before attempting the insert/update, and throw (Raise) your own custom exception in the proc if the check fails, BEFORE attempting the insert update and letting the contraint create the exception...
like image 182
Charles Bretana Avatar answered Nov 30 '25 12:11

Charles Bretana


uh...maybe i'm missing something obvious...but wouldn't it be a better use of your time to fix the bug instead of parsing the exception?

like image 39
Steven A. Lowe Avatar answered Nov 30 '25 12:11

Steven A. Lowe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!