Handle 404 error without using try / catch

2

I have the following code snippet that does an HTTP request , but sometimes the URL does not work, then an exception will be thrown by the framework . >

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Head;

// vai ser lançada uma exceção nessa linha
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

I found examples on the internet that staff adds a block try/catch to control the flow of the program when giving this error, eg:

try
{
  HttpWebResponse response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
   response = ex.Response as HttpWebResponse;
}

Is there another way of not stopping the flow of the program but without using try/catch ? I only want to use try if it is the only solution.

    
asked by anonymous 30.08.2016 / 14:06

2 answers

3

There is no way to resolve this without catching the exception since this was the mechanism adopted by the API.

In theory, you can use another API ( HTTPClient , for example, which by the way is more modern and perhaps more suitable to what you need, see the differences ) or create your own. But no one is going to do it.

There may be some juggling that avoids this, but I can not remember any and I doubt it would be feasible. I actually even imagine encapsulating this API in another one that catches the exception and generate an error code for your code . I do not see any advantage in doing this and in this case I do not even know if it is the most appropriate thing to do.

According to the documentation 4 exceptions are possible in this method . I suppose you're going to consider that the others should be treated by a more general mechanism, right? Just do not go catch Exception to get all, there is double error.

    
30.08.2016 / 14:23
0

Why do not you change to HttpClient ? The return of requests is a HttpResponseMessage which does not throw exceptions in case of failures, unless you use the method EnsureSuccessStatusCode

using (var client = new HttpClient())
{
    var response = await client.PostAsync(uri, content);
    if (response.IsSuccessStatusCode)
    {
        //...
    }        
}
    
31.08.2016 / 09:42