Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap a Linq query in a try/catch block using a method declaration

So here is what I would like to be able to do.

var a = Item.CatchLog().Where(x=>x.Property=="value").Take(10);

or

var a = Item.CatchLog().FirstOrDefault(x=>x.Property=="value");

or

var a = Item.CatchLog().Any(x=>x.Property=="value");

Essentially, I would like is for CatchLog() to basically wrap the execution of the query in a try catch, and Debug.WriteLine() the Exception and then throw it.

Any ideas on how I could implement something like this?

like image 321
Kelly Elton Avatar asked Nov 07 '12 22:11

Kelly Elton


1 Answers

You would need to rewrite your statement, like so:

var a = Item.CatchLog(c => c.Where(x => x.Property=="value").Take(10));

If you allow that, you could write something like:

public static U CatchLog<T,U>(this IEnumerable<T> collection, Func<IEnumerable<T>,U> method)
{
    try
    {
        return method(collection);
    }
    catch(Exception e)
    {
         Debug.WriteLine(e.Message);
         throw;
    }
}
like image 175
Reed Copsey Avatar answered Sep 22 '22 02:09

Reed Copsey