相关疑难解决方法(0)

在使用 Polly 重试之前检查响应的字符串内容

我正在使用一个非常脆弱的 API。有时我500 Server ErrorTimeout,其他时间我还可以得到500 Server Error,因为我给它输入,它不能处理SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

这两种情况都给了我,HttpRequestException但我可以查看来自服务器的回复消息并确定异常的原因。如果是超时错误,我应该再试一次。如果这是一个错误的输入,我应该重新抛出异常,因为再多的重试也无法解决错误数据的问题。

我想对 Polly 做的是在尝试重试之前检查响应消息。但是到目前为止我看到的所有样本都只包含异常类型。

到目前为止,我想出了这个:

        HttpResponseMessage response = null;
        String stringContent = null;
        Policy.Handle<FlakyApiException>()
             .WaitAndRetry(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
              async (exception, timeSpan, context) =>
            {
                response = await client.PostAsync(requestUri, new StringContent(serialisedParameters, Encoding.UTF8, "application/json"));
                stringContent = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == HttpStatusCode.InternalServerError && stringContent.Contains("Timeout"))
                {
                    throw new FlakyApiException(stringContent);
                }
            });
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来进行这种检查?

c# retrypolicy polly

9
推荐指数
1
解决办法
5963
查看次数

标签 统计

c# ×1

polly ×1

retrypolicy ×1