Jacques Boivin
Jacques Boivin

Reputation: 21

Using .NET8, on a "HttpIOException: The response ended prematurely", how can I add retries with exponential backoff?

developing a .Net8 application and currently having a need to perform http request retries when the connection ended prematurely (see ResponseEnded here)...

I wonder if I can use resilience mechanism with Polly and/or Microsoft.Extensions.Http.Resilience ?

Does the resilience retry mechanism will work by default on that exceptional case ? Or it require custom policy or custom delegating handler to do so ?

Thank you

Program.cs

builder.Services.AddHttpClient()
   .AddResilienceHandler("my-pipeline", b => {
     b.AddRetry(new HttpRetryStrategyOptions()); // retry default policies
    });

Upvotes: 1

Views: 1304

Answers (1)

Peter Csala
Peter Csala

Reputation: 22829

The HttpRetryStrategyOptions defines the following triggers:

  • HttpRequestException
  • TimeoutRejectedException
  • greater or equals to HttpStatusCode.InternalServerErrorCode (5XX)
  • HttpStatusCode.RequestTimeout (408)
  • HttpStatusCode.TooManyRequests (429)

So, no it does not trigger automatically for HttpIOException. You have to specify that explicitly, like via a PredicateBuilder:

ShouldHandle = new PredicateBuilder().Handle<HttpIOException>(),
...

UPDATE #1

As it was indicated in the comments the HttpIOException was thrown as an inner exception under a HttpRequestException:

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.HttpIOException: The response ended prematurely. (ResponseEnded) at System.Net.Http.HttpConnection.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)

So, for this use case the default ShouldHandle of the HttpRetryStrategyOptions covers your exception.

If you had to retry only if the HttpIOException is the inner then:

ShouldHandle = new PredicateBuilder().HandleInner<HttpIOException>(),
...

Upvotes: 1

Related Questions