Abstraction of SqlExceptions (using Entity Framework) - c#

I have been using Entity Framework 6 and trying to handle some common problems like Primary/Foreign/Unique Key constraints via EF. EF gives SqlException as an InnerException and it seems that - as far as I found upto now - the only way to understand the actual problem is using error codes in that SqlException object?
I would like to abstract these exceptions by catching EF exceptions and throwing my own exceptions by analyzing the error code in the InnerException. I have some considerations at that point.
SQL Server codes change by the server version or not? Should I handle
different versions of SQL Server in a different way like creating different implementations for 2008, 2012 and etc?
Instead of SQL Server it is possible to use other SQL Servers like
MySQL and its another reason I am trying to abstract these
exceptions.
For example, as in the accepted answer of that question, I would like catch specific errors, but instead of rethrowing I would like to throw my own exception(s). If I do not want to do something special or I do not have any special exception for the error I can create and use a more generic exception in which I can store the original exception into that generic exceptions InnerException field.
I read this blog post and unfortunately the problematic case was my first way to go. I would like to do that without using any third party library as much as possible (of course this is not more important doing it right). I wonder if there is tested and accepted way of doing this, otherwise I am open to any suggestion.

SQL Server codes change by the server version or not?
Exception numbers cannot change once released. Deadlock is and will remain 1205, unique index duplicate key is and will remain 2601, unique constraint violation is and will remain 2627 and so on and so forth. But, you see, in the very examples I choose I show you the danger lurking in relying on these: what decides the difference between 2601 and 2627? Your friendly DBA can decide that it should drop an unique index and instead add an unique constraint (enforce by an index, but that is irrelevant) and all of the sudden your app sees new errors. By doing deep inspection of the exception you add coupling between the application code and the SQL storage, and risk breaking the app when the storage modifies in what would otherwise be a completely transparent change (eg. add an index). Be warned.
I think is feasible to add handling for several well known cases. But you must allow for generic exception you are not aware of ad development time, and handle those.
As for cross-platform, you would have to customize for each platform. The good news is that a 'primary key violation' is the same concept on SQL Server and on MySQL, so you could translate it to a PrimaryKeyViolationException for both providers. Is not trivial, but it is possible.
And finally, a heads up: I've seen folk trying to do similar before, to mix results. The benefits are not exactly overwhelming, and the effort put in is considerable.

Related

Extract structured information from SqlException

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).
Wishfull thinking.
I understand that the entire string comes from the database
Yes, it does. It is a string.
Actually parsing the message is not an option as it is error-prone
Parsing is the ONLY option as there are only 2 items provided by the database: The sql error number and the string. So, either you come up with a generic crystal ball or you work with what you have - which means parsing.
No database that I Know of provides more information mysteriously hidden in the exception - and if it would do so, it would not be a standard approach across databases anyway.

Catching broken database contraints in C# - Best Practice

Say I have an SQL table that has a unique key (or other) constraint on one of the columns.
Then, I have an application (lets go ASP.NET MVC) that allows a user to edit this column.
When the user attempts to save, and the constraint is/will be broken, I need show a user-friendly error message to the user. As such, which of the following is better practice?
Have the application query the database to ensure the constraints are not broken, and then insert/update the row (results in two queries to the db)
OR
Immediately attempt to perform the insert/update, and catch the SqlException should the constraint be broken. I like this, because of only one trip to the db, however how should you then extract which index/constraint was broken and affix the appropriate message? (apart from inspecting Exception.Message?)
1 is the better all-around solution. Db calls are not the only expensive operation, exceptions are costly too. You should really only let your db throw an exception when something goes wrong due to your code, not a user action.
For example, you might later want to install Elmah and get exceptions logged and/or mailed to you. Elmah would log/mail such an exception unless you explicitly told it not to.
Plus like you said, exceptions don't always have the most businessy information to communicate to users (especially SQL exceptions, which are SQL-specific). You have these unique and other constraints for a reason. For those reasons, validate the information before trying to store it.
Take twitter, gmail, etc. When you go to get a username, the application first checks to see if it is taken. These are uniqueness constraints at the application level, which may or may not ultimately be realized as SQL constraints. Since it is your application that faces the user, you should not try to communicate to them by translating from SQL to English.
The problem with option 1 is that it requires the application to have separate distinct knowledge of what the constraints are, which conflicts with a DRY principle, and could lead to problems later when the database constraint gets changed, and the application is not updated - a tight coupling between the data logic, and the application. Also, there is no guarantee of the constraint checks that were performed are still valid at the subsequent pont when you then attempt the update.
This doesn't preclude augmenting your application with some UI layer validation to aid the user before the commit is attempted.
So if that is discarded we are left with option 2, and some translation is necessary somewhere in the application. Where you put that translation and that logic, whether in a Stored Procedurce or a Business Logic layer, is up to you.

Sql Server Compact Edition concurrency / thread safety (i.e. not thread safe)

Over the last few months I have been developing an application using Entity Framework code first and sql server CE for the first time. I have found the combination of the 2 very useful, and compared to my old way of doing things (particularly ADO.NET) it allows for insanely faster dev times.
However, this morning me and some colleagues came across a problem which we have never seen in any documentation regarding SqlServer CE. It cannot handle more than one insert at once!
I was of the opinion that CE may become my database of choice until I came across this problem. The reason I discovered this was in my application I needed to make multiple requests to a web service at once, and it was introducing a bit of a bottleneck so I proceeded to use a Parallel.Invoke call to make the multiple requests.
This was all working fine untill I turned on my applications message logging service. At this point I began to get the following error when making the web requests:
A duplicate value cannot be inserted into a unique index. [ Table name = Accounts,Constraint name = PK__Accounts__0000000000000016 ]
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlServerCe.SqlCeException: A duplicate value cannot be inserted into a unique index. [ Table name = Accounts,Constraint name = PK__Accounts__0000000000000016 ]
Strange I thought. And my first recation was that it must be something to do with the DbContext, maybe the DbContext I was using was static or something else in my Repository class was static and causing the problem, but after sniffing around I was certaing it was nothing to do with my code.
I then brought it to the attention of my colleagues and after a while it was decided it must be SqlServer CE, and after us all setting up different test projects attempting to recreate the problem using threads it was recreated almost every time, and when using Sql Server Express the problem wasn't ocurring.
I just think it is a bit strange that CE cannot handle something as simple as this. I mean the problem is not only with threading - are you telling me that it cannot be used for a web application where two users may insert into a table at the same time...INSANITY!
Anyway, just wondering if anyone else has come across this late into a project like me and been shocked (and annoyed) that it works this way? Also if anyone could shed light on why it is limited in this way that would be cool.
It looks like a bug in SQL CE. See http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=641518

Which .NET exception to throw for invalid database state?

I am writing some data access code and I want to check for potentially "invalid" data states in the database. For instance, I am returning a widget out of the database and I only expect one. If I get two, I want to throw an exception. Even though referential integrity should prevent this from occurring, I do not want to depend on the DBAs never changing the schema (to clarify this, if the primary key constraint is removed and I get a dupe, I want to break quickly and clearly).
I would like to use the System.IO.InvalidDataException, except that I am not dealing with a file stream so it would be misleading. I ended up going with a generic applicationexception. Anyone have a better idea?
InvalidDataException seems pretty reasonable to me:
The name fits perfectly
The description fits pretty reasonably when you consider that it's effectively a data "stream" from the database
Nothing in the description mentions files, so I wouldn't be worried about that side of things
You're effectively deserializing data from a store. It happens to be an RDBMS, but that's relatively unimportant. The data is invalid, so InvalidDataException fits well.
To put it another way - if you were loading the data from a file, would you use InvalidDataException? Assuming you would, why should it matter where the data is coming from, in terms of the exception being thrown?
If you need an exception that would exactly describe the situation you're dealing with, why not make your own exception?
Just inherit it from System.Exception.
I might be tempted to use one of the following:
InvalidConstraintException
NotSupportedException
OverflowException
Or, just go ahead and create my own: TooManyRowsException
You could write a custom exception if you do not find any suitable standard-exception ...
But, you say:
Even though referential integrity
should prevent this from occurring, I
do not want to depend on the DBAs
never changing the schema.
When someone changes the DB schema, changes are pretty big that you'll have to make some modifications to your application / data-access code as well ...

Recommended approach on handling SqlExceptions in db applications

I work on a database application written in C# with sql server as backend. And for data integrity, I try to enforce as much as possible on database level - relations, check constraints, triggers.
Due to them, if data is not consistent, the save / update / insert can fail, and app throw SqlException.
I do various validations both in UI (to present user with meaningful info if data entered is not valid), also in BL, which reports errors back to UI which presents it to user.
However, there are things that really cannot be checked in the app, and are handled by the db: I mean errors on delete when no cascade delete and user try to delete a entity from a master table, etc.
E.g. Employees table acts as master in lot of relations - manager of employee, manager of department, cashier, team leader, teams members etc, etc. If I add anew employee which is not involved in any relation I can delete it, but of user try to delete one that is master oin such relation, the delete fails (as it should) due to RI rules enforced at DB level, and that's ok.
I write delete code in a try ... catch and handle the exception, telling user he cannot delete that employee. But I want to give user more meaningful info - the reason the record cannot be deleted. Maybe it was just a test employee record, which was also added to a test team. But user forget where added that and if I could tell "Cannot delete employee because it is part of team T1", user will know to go first to Team T1, remove user then try to delete it again. That's a simple example, since as I said an employee can be involved in lot of relations - in my app I have at least 20.
The solution is to display the Message reported by SqlException, but that's not elegant at all. First, that msg is very technical - it talks about FK, PK, Triggers, which are meaningless for users and will scare them. Second my app is uses multi-lang UI and all menus and msgs are shown in user selected language (selected either at login time or in user profile). And the msg from SqlException is english (if I use english version) or worst, less common languages, like german or dutch, if it happens that sql server is in that language.
Is there any common or recommended approach to extract meaningful info from sql exception to be able to present user a meaningful msg (e.g. what relation or child table caused the failure, or what trigger, etc). but something I can test in program in a lang-independent fashion and then format my own error msg in a user-friendly way?
How do you handle this situation?
Thanks for all answers
(PS: Sorry for the long post)
Unfortunately, there isn't an easy answer here.
The amount of work involved will depend on the consistency of your error messages coming from your business layer. You are going to need to do some form of translation from the "technical" error message to your user oriented message.
This should be a matter of making some forms of lookups from your error messages to a resource key, which can be used to pull out your language-specific error message. However, if you need to parse the messages for more information (ie: table names, etc), then it gets a bit trickier. In that case, you'll probably need to have something that maps an error message to a regex/processor of some form as well as a new resource string. Then you could format the user's string with the information you extract from the original error, and present it to the user.
Well, from the database, you'll only ever get these technical messages, e.g. "violation of foreign key relation FK_something_to_another" or such.
Typically, in the SqlException, you also get a SQL error code or something else.
The best approach would probably be to have a separate table in your database which basically maps those technical SQL errors that can happen to more meaningful, user-oriented messages. E.g. if your SQL error says something like "fk violation blablabaal", you could have an entry in your "UserErrorTable" which maps this to a user message saying "could not delete user (this.and.that), most likely because ..... (he's still member of a team)" or whatever.
You could then try to catch those SqlExceptions in your business layer, translate those technical infos into a custom exception for your users, put in a user-friendly message, and stick the technical exception into the .InnerException of your custom exception type:
public class UserFriendlyException : Exception
{
public string UserErrorMessage { get; set; }
public UserFriendlyException(string message, SqlException exc) : base(message, exc)
{
UserErrorMessage = MapTechnicalExecptionToUserMessage(exc);
}
}
Marc
The short answer is "don't." Let the errors bubble out to the global error handling/logging. The validation and business rules should generally preclude database exceptions, so you are better off failing hard and fast and not submitting dirty data. Transactions help too.
Error Messages do not equate Exceptions. An error message is something that the user should find informative and most important actionable. There are some guidelines around error messages in the User Experience Guidelines I recommend you read up. Apple also has good generic guidelines in Writing Good Alert Messages.
You'll immediately notice that most, if not all, of SQL errors are not good end user messages. 'Constraint FKXF#455 violation' - Bad error for end user. 'Filegroup is full' - Bad error for end user. 'Deadlock' - same. What good applications do is they separate the roles of users. Administrators need to see these errors, not end users. So the application always logs the full SQL error with all the details, eventually notifies the administrator, and then display a different error to the user, something like 'A system error occurred, the administrator was notified'.
If the SQL error can is actionable by the end user, then you can display him an error message instruct him what to do to fix the problem (eg. change the invoice date in the input to satisfy a constraint). But even in this case most times you should not display the SQL error straight to the user ( you already seen a very good reason why not: localization). I understand that this creates a much bigger workload for your development team. You must know what errors are user actionable in each case, from the multitude of errors you may catch. That is well known, and that's exactly why good program managers know that about 80% of the code is handling the error cases, and why the application being 'done' usually means is 20% done. This is what differentiates great apps from ordinary ones: how they behave when things go wrong.
My suggestion is to start up with the principle of progressive disclosure. Display an generic error message stating 'the operation has failed'. Offer to display more details if the user presses a 'Show details...' button on the error message dialog, and display the SqlError collection (btw, you should always log and display the entire SqlError collection of SqlException.Errors, not the SqlException). Use the SqlError.Number property to add logic in the catch block that decides if the user can do anything about the error (decide if the error is actionable) and add appropriate information.
Unfortunately there is no pixie dust. You are touching the foot hils of what is probably the most difficult part of your project.
The way to do this is to write a stored procedure, and use TRY and CATCH. Use RAISERROR to raise your own custom messages, and check the error code in the SqlException.
We usually write some sort of translator in our projects.We compare the SQL exception message with some predefine patterns and show the equivalent message to user
About generic technical > userfriendly errors i can only support the answers already giving.
But to your specific example with the employer i must encourage you to not rely only on the SqlException. Before trying to delete the Employee you should make some check to see if he/she is a part of any teams, is manager etc. It will tremendiosuly improve the usability of your application.
Pseudo:
Employee e;
try {
IEnumerable<Team> teams = Team.GetTeamsByEmployee(e);
if (teams.Count() > 0) {
throw new Exception("Employee is a part of team "+ String.Join(",", teams.Select(o => o.Name).ToArray());
}
IEnumerable<Employee> managingEmployees = Employee.GetEmployeesImManaging(e);
if (managingEmployees.Count() > 0) {
throw new Exception("Employee is manager for the following employees "+ String.Join(",", managingEmployees.Select(o => o.Name).ToArray());
}
Employee.Delete(e);
} catch (Exception e) {
// write out e
}
Errors happen. When it doesn't particularly matter what kind or type of error you hit, or how you handle it, slapping your code in a TRY...CATCH... block and write a generic error reporting system is fine. When you want (or are required to) write something better than that, it can take serious effort, as outlined in some prior posts (which I too have upvoted).
I tend to classify errors as anticipatable or unanticipatable. If you can anticipate an error and you want to handle it with a clear an consice message, such as with your "delete employee" situation, you will have to plan and code accordingly. By their definition, you cannot do this for unanticipatable errors--that's usually where TRY/CATCH comes in.
For your situation, one way could be before deleting the row, check via queries against the child tables whether or not the delete could succeed. If it won't, you'll know precisely why (and for all child tables, not just the first one that would block the delete), and can present the user with a clear message. Alas, you must consider whether the data can change between the check and the actual delete -- perhaps not a problem here, but it could be in other situations.
An alternative based on the TRY...CATCH... would be to check the error number within the catch block. If it's a "can't delete due to foreign key", you could then query the children tables and generate the message, and if it was some other unanticipated error, you'd have to fall back on a generic message.
(A caveat: some times when it hits an error, SQL will raise two error messages in a row [is the FK constraint violation one of them?] and in these situations the various ERROR() functions will only return data for the second and invariably less useful message. This is incredibly aggravating, but there's not too much you can do about it.)
In summary I would caution against relying on SQL exceptions and errors. For me, if we rely on such errors we are storing up trouble. Such error messsages are normally not user readable. In addition UI developers may say "oh well, it will be caught by the database guys, I do not need to validate that". Totally incorrect!
Perhaps a better approach would be to ensure that validation prevents these issues in the first place. e.g. If you cannot delete object A because it is referenced by object B, then we should implement some kind of dependency service at a level higher than the database. It depends what kind of application it is.
Another example would be string length validation. Do we really want to rely on the database validation for checking string length of fields entered by the user. Of course, this is an extreme case!
Normally, if the database layer is throwing an exception it can be a sign of a bug elsewhere. With a client/server setup we can assert that validation is the responsibility of both. If it makes it to the database then normally it is too late.
You may want to use RAISEERROR so the calling code can be fed with an exception from a stored procedure. From that you can provide a sensible error message.
There is never a one size fits all approach. My motto here would be prevention is better than cure! Validate earlier rather than later.

Categories

Resources