What is the proper way to catch and identify the 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'”?
I want to be able to catch and identify the exceptions that belong to this specific type and then return a suitable error message. What is the proper way to do that in a catch block?
2 Answers
2
The exception you need to catch is an HttpRequestException
specifically with an InnerException
that is a WebException
and has a Status
property with a value of WebExceptionStatus.NameResolutionFailure
.
HttpRequestException
InnerException
WebException
Status
WebExceptionStatus.NameResolutionFailure
Fortunately, using C# 6.0 exception filters, it's now easy to catch only an exception that fulfills these specific criteria:
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");
}
First, catch HttpRequestException in catch block
catch (HttpRequestException ex){}
Then if you need to closely identify the message, use ex.Message
if (ex.Message.StartsWith("The remote name could not be resolved:"))
{
//do the rest
{
Fails in any non-English locale.
– spender
Jun 29 at 10:00
Not sure. Last time I wanted to use HResult it was giving me same HResult code for different exceptions, but I don't remember it well so you should try it
– tomassino
Jun 29 at 10:01
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
What about using the HResult instead of the exception message?
– Nimish David Mathew
Jun 29 at 9:57