method to call other methods and handle exceptions

Background:

I wrote a C# application that is calling multiple methods from a web service. Methods are being called from loops in Main, from some classes, and so on. Each of these methods may fail because of same reasons:

  • Connection timeout
  • Web service internal error
  • Session expiry

If any of these methods fail, I just need to wait for a few seconds (or call a log-in method), and call them again.

Problem:

I don't want to write essentially the same try/catch block for every call to all of those methods, so I need another universal method, that would be able to call all the other methods with no regard to it's name and parameters, then catch some common exceptions, call the method again if necessary, and return the values.

Methods delegation ring a bell, but I don't really know how to approach this problem. Any help would be appreciated.

Jon Skeet
people
quotationmark

It sounds like you probably want something like this:

private T CallWithRetries<T>(Func<T> call)
{
    // TODO: Work out number of retries, etc.
    for (int i = 0; i < 3; i++)
    {
        try
        {
            return call();
        }
        catch (FooException e)
        {
            // Determine whether or not to retry, log etc. If this is the
            // last iteration, just rethrow - or keep track of all the exceptions
            // so far and throw an AggregateException containing them.
        }
    }
    throw new InvalidOperationException("Shouldn't get here...");
}

Then:

// Or whatever you want to do...
int userId = CallWithRetries(() => webService.GetUserId(authentication));

You can have a similar method with an Action parameter for any calls which don't return a value.

people

See more on this question at Stackoverflow