You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
95 lines
2.9 KiB
C#
95 lines
2.9 KiB
C#
using HttpClientStudy.Config;
|
|
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace HttpClientStudy.Core
|
|
{
|
|
/// <summary>
|
|
/// Http 错误处理
|
|
/// <list type="number">
|
|
/// <listheader>
|
|
/// <term>常见方式</term>
|
|
/// <description>(仅个人见解)</description>
|
|
/// </listheader>
|
|
/// <item>
|
|
/// <term>HtppClient 提供的状态码、EnsureSuccessStatusCode()等机制</term>
|
|
/// <description>(适用HttpClient内部错误)</description>
|
|
/// </item>
|
|
/// <item>
|
|
/// <term>Try Catch 方式</term>
|
|
/// <description>(适用外部)</description>
|
|
/// </item>
|
|
/// <item>
|
|
/// <term>HttpClient 管道</term>
|
|
/// <description>(统一处理)</description>
|
|
/// </item>
|
|
/// <item>
|
|
/// <term>使用 Polly 类库</term>
|
|
/// <description>(更多功能,也可结合HttpClient管道)</description>
|
|
/// </item>
|
|
/// </list>
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// 错误处理
|
|
/// </remarks>
|
|
public class HttpError
|
|
{
|
|
// 定义一个 HttpClient 共享实例
|
|
public static HttpClient HttpClient = new HttpClient(new SocketsHttpHandler() { PooledConnectionLifetime = TimeSpan.FromMinutes(1) })
|
|
{
|
|
BaseAddress = new Uri(WebApiConfigManager.GetWebApiConfig().BaseUrl)
|
|
};
|
|
|
|
/// <summary>
|
|
/// 未知主机错误
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public async Task<HttpStatusCode> UnknownHostAsync()
|
|
{
|
|
var response = await HttpClient.GetAsync("http://www.unknowhost_nonono.com/404.html");
|
|
|
|
return response.StatusCode;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 没有服务(WebApi服务未启动)
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public async Task<HttpStatusCode> NoServiceAsync()
|
|
{
|
|
try
|
|
{
|
|
var response = await HttpClient.GetAsync("http://localhost:30");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// 捕获异常,处理
|
|
await Console.Out.WriteLineAsync(ex.Message );
|
|
throw;
|
|
}
|
|
|
|
return HttpStatusCode.OK;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 404错误
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public async Task<HttpStatusCode> Http404Async()
|
|
{
|
|
var response = await HttpClient.GetAsync("/404.html");
|
|
return response.StatusCode;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 服务器错误
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public async Task<HttpStatusCode> Http500Async()
|
|
{
|
|
var response = await HttpClient.GetAsync("/api/ErrorDemo/Error500");
|
|
return response.StatusCode;
|
|
}
|
|
}
|
|
}
|