Be careful how you filter .NET Exceptions

Here’s a very silly issue I hit the other day.  It involves the classic use (or abuse?) of the LINQ operator SingleOrDefault but unexpectedly getting more than one result returned.  In this case an upgrade to a component had changed how data was stored in a SqlLite database; we hadn’t changed the schema, just the number of versions of data we stored per item.

It was quickly found and we placed an exception around our call to SingleOrDefault and filtered the exception to clean up the database, as shown in this simplified code.

try

{  

  getDocument = DocStore.SingleOrDefault(d => d.SelfLink = doc.SelfLink); 

}

catch (System.InvalidOperationException ex)

{    

  if (ex.Message == “Sequence contains more than one matching element”)  

  {     

    CleanUpDuplicates(doc.SelfLink);  

  }  

 else  

 {    

    throw;  

  }

}

This was all caught in regression testing, had more testing to verify the fix and so we were safe to release for upgrades.

Then we get a support call from a test user who says the very situation that we believed we had fixed had just occurred with their system.  A quick check in the logs and it is indeed the same issue.  Only, they are running the system on a Norwegian language version of Windows.  Who knew that the .NET framework very kindly provides localization for exception messages?  This makes sense, it’s the kind of thing a user might see in a dialog box.  Here is what “Sequence contains more than one matching element” becomes in Norwegian,

        Sekvensen inneholder mer enn ett samsvarende element

Oh dear.  So our filtered exception handling has failed when used on a non-English system.  Instead we are now catching that InvalidOperationException, then performing a proper check for multiple rows before dealing with them, rather than relying on the text of the exception message.

Lesson learned.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s