捕获和识别 HttpRequestException "The remote name could not be resolved: 'www.example.com'" 的正确方法是什么?
What is the proper way to catch and identify the HttpRequestException "The remote name could not be resolved: 'www.example.com'"?
我希望能够捕获并识别属于此特定类型的异常,然后 return 一条合适的错误消息。在 catch 块中执行此操作的正确方法是什么?
首先,在 catch 块中捕获 HttpRequestException
catch (HttpRequestException ex){}
然后如果您需要仔细识别消息,请使用 ex.Message
if (ex.Message.StartsWith("The remote name could not be resolved:"))
{
//do the rest
{
您需要捕获的异常是 HttpRequestException
特别是 具有 InnerException
的 WebException
和 Status
属性 值为 WebExceptionStatus.NameResolutionFailure
.
幸运的是,使用 C# 6.0 exception filters,现在很容易只捕获满足这些特定条件的异常:
var hc=new HttpClient();
try
{
(await hc.GetStringAsync("https://www.googggle.com"));
}
catch(HttpRequestException ex)
when ((ex.InnerException as WebException)?.Status ==
WebExceptionStatus.NameResolutionFailure)
{
//yay. localization-proof
Console.WriteLine("dns failed");
}
我希望能够捕获并识别属于此特定类型的异常,然后 return 一条合适的错误消息。在 catch 块中执行此操作的正确方法是什么?
首先,在 catch 块中捕获 HttpRequestException
catch (HttpRequestException ex){}
然后如果您需要仔细识别消息,请使用 ex.Message
if (ex.Message.StartsWith("The remote name could not be resolved:"))
{
//do the rest
{
您需要捕获的异常是 HttpRequestException
特别是 具有 InnerException
的 WebException
和 Status
属性 值为 WebExceptionStatus.NameResolutionFailure
.
幸运的是,使用 C# 6.0 exception filters,现在很容易只捕获满足这些特定条件的异常:
var hc=new HttpClient();
try
{
(await hc.GetStringAsync("https://www.googggle.com"));
}
catch(HttpRequestException ex)
when ((ex.InnerException as WebException)?.Status ==
WebExceptionStatus.NameResolutionFailure)
{
//yay. localization-proof
Console.WriteLine("dns failed");
}