Search code examples
c#dotnet-httpclientpollyretry-logic

Retry Pattern via polly


Please let me know is there any chance in the below code the "response" turns to be null, that results an error if I try to get response.result and response.statuscode value in onRetry block.

Sample code below

AsyncRetryPolicy<HttpResponseMessage> retryPolicyPost = Policy
    .Handle<HttpRequestException>()
    .OrResult<HttpResponseMessage>(r => r != null && (!r.IsSuccessStatusCode))
    .WaitAndRetryAsync(3, times => TimeSpan.FromMilliseconds(times * 30000),
        onRetry: (response, delay, retryCount, context) =>
        {
            Console.WriteLine(retryCount);
            Console.WriteLine(response.Result);
            Console.WriteLine(response.Result.StatusCode);
        });

I appreciate your response.


Solution

  • is there any chance in the below code the "response" turns to be null

    Your response parameter's type is DelegateResult<HttpResponseMessage>, which can't be null inside the onRetry delegate.

    BUT the response.Result can be null! The DelegateResult defines two properties which are mutually exclusive: Exception, Result.

    So, if the retry logic is triggered because an HttpRequestException was thrown then response.Result will be null, but the result.Exception will be an HttpRequestException.

    If the retry logic is triggered because the HttpResponseMessage's StatusCode is different than 200 then response.Result will be an HttpResponseMessage, but the result.Exception will be null.


    This this piece of code is error-prone, it might throw NRE:

    Console.WriteLine(response.Result.StatusCode);
    

    To fix this you can do the following:

    var statusCode = response.Result?.StatusCode ?? ((HttpRequestException)response.Exception).StatusCode;
    Console.WriteLine(statusCode);
    

    Please note that HttpRequestException's StatusCode returns with an HttpStatusCode?.