ASP.NET Database Tracking Error
I'm curious about how people catch certain database errors in .NET, especially foreign key or unique index violations. Coming from the classic ASP / VB background, my first tilt is to check for the error number to then create a friendly message to the user that something is wrong. However, I would have thought that there are things like SqlForeignKeyException or similar in the .NET world. If such a thing exists, I cannot find it in the documentation anywhere. How do you handle such errors?
a source to share
If your application generates foreign key or unique index violations, there might be something wrong with the application and its developers need to notify it, not the users. That is, usually the input validation that the user provides should prevent these kinds of exceptions from being thrown.
The general approach is to catch unhandled errors in the Application_Error event and write them to a file or database. There are also tools that can help with error logging like ELMAH
A generic message will just be generated for the user ... but developers should keep an eye on the error logs. See Jeff Atwood's post on Exception-Based Management .
Edit: To answer the other part of your question - there are many different Exception objects in .NET, but most SQL exceptions seem to go through the generic SqlException class. You can learn more about errors by examining the Message and StackTrace () properties and rolling into the InnerException property. Something like a foreign key violation might manifest as an HttpException with a SqlException nested inside it.
a source to share
Speaking of SqlException, you should be using SQL Server -
If you want to know if it was a foreign key error, check the internal SqlExceptions and check the Number property. This number corresponds to the entry in the master.dbo.sysmessages table, numbers from 0 to 50000 are SQL errors, 50000+ are user-defined.
Remember to rebuild errors - SQL may return more than one.
If you are using a return value check this also . You will need to read the TSQL source code to see if this special type of error message is being used.
Warnings are errors of level 10 or less and must be captured through the SqlInfoMessage event.
If the program returns an @@ error, make sure to save it as the @@ error is reset for success on the next next command in the package.
a source to share