Handle Exceptions in Find

If it’s repetitive, it can be automated. Think about the following requirements. Have you ever hoped there would be a better way to implement them?

  • INotifyPropertyChanged
  • Undo/redo
  • Code contracts (preconditions)
  • Logging
  • Transaction handling
  • Exception handling
  • Thread dispatching
  • Thread synchronization
  • Immutable
  • Authorization
  • Audit
  • Caching
Generally we will be doing this

        private SearchResults<DummyObject> GetResults()
        {
            try
            {
                var query = client.Search<DummyObject>();
                var results = query.Take(10).StaticallyCacheFor(TimeSpan.FromMinutes(5)).GetResult();
                return results;
            }
            catch (ServiceException exception)
            {
                //Blah blah
            }
            catch (ClientException exception)
            {
                //Blah blah
            }
        }

There are few issues in above code 

  • Exception code will be repititive and will expand the class after some time.
  • Mixing code in business logic.
  • More than one responsibilities in one object.

There are many ways to deal with this but here PostSharp is my friend.

//Add Attribute
[HandleException(“Exception In Find”)]
private SearchResults<DummyObject> GetResults()
{
       var query = client.Search<DummyObject>();
       var results = query.Take(10).StaticallyCacheFor(TimeSpan.FromMinutes(5)).GetResult();
       return results;
}
//Create an Aspect
[Serializable]
public class HandleExceptionAttribute : OnExceptionAspect
{
     private string message;
    public HandleExceptionAttribute(string message)
    {
        this.message = message;
    }
    public override void OnException(MethodExecutionArgs args)
    {
        args.FlowBehavior = FlowBehavior.Continue;
        string errorMessage = string.Empty;
        switch (args.Exception.GetType().Name)
        {
            case “ServiceException”:
                errorMessage = “Service is down, or if there is any other communication problem.”;
                break;
            case “ClientException”:
                errorMessage = “Query contains errors that is found at runtime”;
                break;
        }
        Console.WriteLine(string.Format(“{0} – {1}”, message, errorMessage));
     }
}