Search code examples
c#.netasync-awaitdotnet-httpclient

How to deal with HTML error codes and timeout from HttpClient()


I'm using HttpClient to connect to a server (see simplified code below). I cant figure out how I would respond to HTML error codes (e.g. 403) and timeouts so I can report what the result is.

When I encounter a 403 error code an error pop-up occurs in Visual Studio. But I can figure out how I convert this into try in the code. i.e. is the name of the exception present in the error pop-up?

using System.Net.Http;

HttpClient client = new HttpClient();
var response = client.PostAsync(dutMacUrl, null).Result;
var result = response.Content.ReadAsStringAsync().Result;

Solution

  • you can use async/await feature to simplify your code and avoid using Result.

    for example

    public async Task<string> Foo(string uri)
    {
        var client = new HttpClient();
        try
        {
            var response = await client.PostAsync(uri, null);
        }
        catch (Exception ex)
        {
            //here you handle exceptions
        }
    
        // use this if (response.StatusCode != HttpStatusCode.OK) { do what you want }
        // or this if (response.IsSuccessStatusCode) { do what you want }
        var result = await response.Content.ReadAsStringAsync();
        return result;
    }