exception doesn't get caught within try/catch func delegate

Viewed 68

I'm attempting to use a re-usable try/catch for executing Kusto queries in C# like so:

public static T DoWithRetry<T>(Func<T> func, TimeSpan sleepPeriod, int tryCount = 3)
        {
            if (tryCount <= 0)
                throw new ArgumentOutOfRangeException(nameof(tryCount));

            while(true)
            {
                try
                {
                    return func();
                }
                catch (Exception ex)
                {
                    if (--tryCount == 0)
                        throw;
                    Console.WriteLine($"Encountered exception {ex.Message}");
                    Console.WriteLine($"Retrying in {sleepPeriod}...");
                    Thread.Sleep(sleepPeriod);
                }
            }            
        }

And then calling it like so:

try 
{

    var res = DoWithRetry(() =>
    {
       return kustoClient.ExecuteQuery($"KustoQuery");
    }, TimeSpan.FromMinutes(3));
}
catch (Exception ex)
{
    Console.Error.WriteLine($"Exception Message: {ex.Message}");
    return "failed, please check.";
}

Edited to include outer try/catch in example

However when Kusto throws a throttle exception, the exception is never caught inside the DoWithRetry try/catch, instead the outer try/catch. If I were to throw my own exception in the lambda like so:

var res = DoWithRetry(() =>
{
   throw new KustoRequestThrottledException();
}, TimeSpan.FromMinutes(3));

it is caught within the DoWithRetry try/catch. What could be preventing the kusto exception from being caught within the DoWithRetry try/catch?

1 Answers

It turns out the execution of the query doesn't occur until the data is accessed later (In my case, I pass IDataReader into another function and perform .Read()). I ended up passing in the function which performs that read in the try/catch instead.

Related