Harrison
Harrison

Reputation: 3953

Catching exception (and ignoring) in called method, but need to throw it in caller

I have a method that tries to get a web page. I want to attempt to get it several times so I built a wrapper around it to retry several times. In the method called I catch and then ignore the exception returning null. Therefore, after the first attempt the retries will occur. Here is the called method:

internal static async Task<string> WebClientAsync(string URI, NetworkCredential Creds = null, Dictionary.FantasySite Site = Dictionary.FantasySite.Other)
{
    if (Creds == null)
    {
        try
        {   //attempt to get the web page
            HttpClient client = new HttpClient(); //create client
            HttpResponseMessage response = await client.GetAsync(URI);  //get response
            response.EnsureSuccessStatusCode(); //ensure the response is good (or throw Exception)
            return await response.Content.ReadAsStringAsync();  //return the string back
        }
        catch (HttpRequestException)
        {
            //MessageBox.Show(string.Format("\nHttpRequestException Caught!\nMessage :{0} for URI {1}.", e.Message, URI));
            return null;  //Catch the exception because we wrapped this and are trying again (null is the indicator it didn't work)
        }
        catch (Exception)
        {
            //MessageBox.Show(string.Format("\nException Caught!\nMessage :{0} for URI {1}.", e.Message, URI)); //TODO - THis hasn't happened, but remove it for production
            return null; //Catch the exception because we wrapped this and are trying again  (null is the indicator it didn't work)
        }
    }

}

If this still fails after all the retries then I want to throw the exception, but since I threw it away, I can't. Here is the calling method.

internal static async Task<string> WebClientRetryAsync(string URI, NetworkCredential Creds = null, Dictionary.FantasySite Site = Dictionary.FantasySite.Other)
{
    string webPage = null;
    for (int i = 0; i < Dictionary.WEB_PAGE_ATTEMPTS; i++)  //Attempt to get the webpage x times
    {
        System.Diagnostics.Debug.Print(string.Format("WebClientRetryAsync attempt {0} for {1}", i + 1, URI));
        //wait some time before retrying just in case we are too busy
        //Start wait at 0 for first time and multiply with each successive failure to slow down process by multiplying by i squared
        Thread.Sleep(Wait.Next(i * i * Dictionary.RETRY_WAIT_MS));
        webPage = await WebClientAsync(URI, Creds, Site);
        if (webPage != null) { break; } //don't attempt again if success
    }
    /*TODO - If webPage is null we didn't have success and need to throw an exception.  
     * This is done in the calls to this method and should be done here, move code over */
    return webPage;
}

Can someone suggest if this is a bad approach and how I could refactor the code to throw the exception after failing too many times? Should I pass the exception to the calling method and ignore it until the retries have run out?

Upvotes: 2

Views: 527

Answers (1)

Alex
Alex

Reputation: 13224

Yup. You should not throw away exceptions that you wish to rethrow. One possible approach is the following (trying to make a minimal amount of modifications to your current code):

internal static async Task<string> WebClientAsync(string URI, NetworkCredential Creds = null, Dictionary.FantasySite Site = Dictionary.FantasySite.Other)
{
    // If (Creds == null) removed, you must return a task or throw an exception.

    //attempt to get the web page
    HttpClient client = new HttpClient(); //create client
    HttpResponseMessage response = await client.GetAsync(URI);  //get response
    response.EnsureSuccessStatusCode(); //ensure the response is good (or throw Exception)
    return await response.Content.ReadAsStringAsync();  //return the string back
}

internal static async Task<string> WebClientRetryAsync(string URI, NetworkCredential Creds = null, Dictionary.FantasySite Site = Dictionary.FantasySite.Other)
{
    // assumes you have .NET 4.5, otherwise save exception.
    // uses System.Runtime.ExceptionServices;
    ExceptionDispatchInfo exceptionDispatchInfo = null; 

    for (int i = 0; i < Dictionary.WEB_PAGE_ATTEMPTS; i++)  //Attempt to get the webpage x times
    {
        System.Diagnostics.Debug.Print(string.Format("WebClientRetryAsync attempt {0} for {1}", i + 1, URI));
        try
        {
            var webPage = await WebClientAsync(URI, Creds, Site);
            return webPage;
        }
        catch (Exception ex)
        {
            // save exception so it can be rethrown.
            exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex);
        }
        // Edit: also need to do an async wait (no thread.sleep):
        if (i < Dictionary.WEB_PAGE_ATTEMPTS - 1)
        {
            //wait some time before retrying just in case we are too busy
            //Start wait at 0 for first time and multiply with each successive failure to slow down process by multiplying by i squared
            await Task.Delay(Wait.Next(i * i * Dictionary.RETRY_WAIT_MS));
        }
    }
    Debug.Assert(exceptionDispatchInfo != null); // shouldn't be null if we get here.
    exceptionDispatchInfo.Throw();
}

Upvotes: 3

Related Questions