-1

Below code re-try 2 times when we have error from HttpRequestException, 5XX and 408 and it's works fine.

Here I want to re-try for even 401 error? how we can achieve this with Polly?

 services.AddHttpClient(Options.DefaultName)
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { })
            .AddPolicyHandler(HttpPolicyExtensions.HandleTransientHttpError()
                .WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
user584018
  • 10,186
  • 15
  • 74
  • 160
  • What is your reason for `.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { })`? Isn't that the default already without manually specifying it? – ProgrammingLlama Sep 01 '21 at 05:57
  • 2
    Why do you want retry the same request if you receive `Unauthorized`? Issuing the same request normally does not give you new credentials. Or did I miss something? – Peter Csala Sep 01 '21 at 07:17
  • We will perform again ReAuthorize in case 401. – user584018 Sep 01 '21 at 14:47
  • 1
    @user584018 Exactly, whenever you encounter a 401 then you want to perform a *specific action* rather than issuing the same request. That's why I don't get it why do you want to include 401 into your generic retry logic. – Peter Csala Sep 02 '21 at 06:29

1 Answers1

5

Add .OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized) to your code:

services.AddHttpClient(Options.DefaultName)
        .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { })
        .AddPolicyHandler(HttpPolicyExtensions.HandleTransientHttpError()
        .OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
        .WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));

I would suggest rewriting your code like this to make it easier to read:

services.AddHttpClient(Options.DefaultName)
        .AddTransientHttpErrorPolicy(builder => 
            builder
                .OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                .WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))))
        );
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86