Handle 404 error without using Try/catch

Asked

Viewed 379 times

5

I have the following code snippet that makes an HTTP request, only that sometimes the URL does not work, then will be launched an exception by 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 people add a block try/catch to control the program flow when this error occurs, example:

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

There is another way not to stop the program flow but without using try/catch? I just want to use try if it is the only solution.

2 answers

6


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

In theory it is possible to use another API (Httpclient, for example, which by the way is more modern and perhaps more suited to what you need, see the differences) or create your own. But no one will do that.

There may be some juggling that prevents that, but I can’t think of any and I doubt it would be viable. I actually imagine encapsulating this API in another that captures the exception and generates an error code for your code to consume. I see no point in doing that and in this case I don’t even know if it’s the right thing to do.

According to the documentation 4 exceptions are possible in this method. I imagine you’ll consider that the others should be treated by a more general mechanism, right? Just don’t go capture Exception to catch all, there is double mistake.

1

Why don’t you switch to the HttpClient? The return of requests is a Httpresponsemessage which makes no exceptions in case of failures, except if you use the method EnsureSuccessStatusCode

        // client é uma instancia da classe HttpClient, que 
        // deve ser instanciada apenas uma vez por aplicação conforme 
        // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?WT.mc_id=DOP-MVP-5002397&view=netcore-3.1#examples
        var response = await client.PostAsync(uri, content);
        if (response.IsSuccessStatusCode)
        {
            //...
        }        
  • Thanks for remembering, @Augustovasques. Even not having many 'upvotes' in my reply, I made the correction and remark that you mentioned, not to encourage the wrong use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.