HttpResponseMessage.EnsureSuccessStatusCode()
的使用模式是什么?它处理消息的内容并抛出HttpRequestException
,但我看不出如何以编程方式处理它,这与通用Exception
有什么不同。例如,它不包括HttpStatusCode
,这会很方便。
有什么方法可以从中获取更多信息吗?有没有人可以同时展示EnsureSuccessStatusCode()
和HttpRequestException的相关使用模式?
发布于 2015-01-16 22:43:00
我不喜欢EnsureSuccessStatusCode,因为它没有返回任何有意义的东西。这就是为什么我创建了自己的扩展:
public static class HttpResponseMessageExtensions
{
public static async Task EnsureSuccessStatusCodeAsync(this HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
return;
}
var content = await response.Content.ReadAsStringAsync();
if (response.Content != null)
response.Content.Dispose();
throw new SimpleHttpResponseException(response.StatusCode, content);
}
}
public class SimpleHttpResponseException : Exception
{
public HttpStatusCode StatusCode { get; private set; }
public SimpleHttpResponseException(HttpStatusCode statusCode, string content) : base(content)
{
StatusCode = statusCode;
}
}
微软EnsureSuccessStatusCode的源代码可以在here上找到
基于SO link的同步版本:
public static void EnsureSuccessStatusCode(this HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
return;
}
var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
if (response.Content != null)
response.Content.Dispose();
throw new SimpleHttpResponseException(response.StatusCode, content);
}
我不喜欢IsSuccessStatusCode的原因是它的可重用性不是很好。例如,您可以使用像polly这样的库在网络出现问题的情况下重复请求。在这种情况下,您需要您的代码引发异常,以便polly或其他库可以处理它……
发布于 2019-08-11 05:06:43
当我不想在同一个方法上处理异常时,我使用EnsureSuccessStatusCode。
public async Task DoSomethingAsync(User user)
{
try
{
...
var userId = await GetUserIdAsync(user)
...
}
catch(Exception e)
{
throw;
}
}
public async Task GetUserIdAsync(User user)
{
using(var client = new HttpClient())
{
...
response = await client.PostAsync(_url, context);
response.EnsureSuccesStatusCode();
...
}
}
将在DoSomethingAsync上处理在GetUserIdAsync上抛出的异常。
https://stackoverflow.com/questions/21097730
复制相似问题