I made a catch, that if a specific sql server error is thrown, that the code can dis-regard and carry on. A co-worker said that the error message I’m catching is being thrown from SQL and it may change when we upgrade to 2008. He said my solution will work today, but it is a weak solution. So, my question is…How should I catch and handle a error thrown from SQL server, if it may be dependend on the sql server version. ie(2005, 2008 or newer)? Any ideas on how to make the catch better?
My code
string sqlError = "The INSERT statement conflicted with the FOREIGN KEY constraint Table1. The conflict occurred in database Work1, table Table2.";
catch (Exception oExp)
{
//This check will allow the specific error to continue without getting caught.
if (oExp.Message.Contains(Constants.sqlError) == false)
{
throw oExp;
}
}
As noted in the comments, this is avoidable so you should do the right thing and make sure it can’t happen in the first place.
And as you’ve surmised, using static text is a bad thing. This is even more true when you consider that these messages will change depending on the LANGUAGE that SQL Server is installed with or the user is logged on as (as SQL messages are locale sensitive), regardless of upgrade level.
Also … I don’t quite understand why you’d want to continue even if this error is thrown as it sounds like it puts your data into an inconsistent state, so I’d review whether you’re doing the right thing in the first place. However I don’t know your application…
So with all those caveats said … in the event that avoiding this is not possible (for whatever reason – excluding laziness 🙂 ), rather than catch a generic
Exception, you should catch aSqlException, which includes theStateandNumberproperties which you should be able to use verbatim.