Item-based exception handling in LINQ
Last week I rewrote some of my client’s code after having discovered a number of bugs. More specifically, a lot of errors came up in LINQ methods such as Where and Select. In order to capture what exactly was going wrong there, I have added a new extension method to the IEnumerable interface, allowing item-based exception handling on collections and LINQ statements.
The advantage of this code is that you could use it like any other LINQ method, like this method for example:
All errors that have risen during the previous methods in the chain will be in scope of this method. What you want to do with these errors can be defined in the delegate (with the exception as the sole parameter). This also means the position of the method is important: methods called after this statement won’t be covered by your delegate in the event of errors!
Assume this example:
I have placed the CatchExceptions method between the Where and the Select extension method. Let’s say something goes wrong during the projection in the Select method. As the new extension method has no clue what collection comes after him (only the collection what comes just before!), it won’t handle those errors. If you would locate the new method back to its original place, it would capture the errors from the Select statement as well.
This is a very good example how useful this new method is. The code attempts to filter out empty folders. Because the code needs to navigate to each folder and count the number of items in it, it is possible there are some security restrictions. If that’s the case it will throw an SecurityException. The new method ensures every error is caught without requiring the loop to exit (or to include error handling in other methods), allowing clean code and separation of business logic.
It might not be a silver bullet but at least it’s an interesting utility. The original source of the code can be found here.