Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 89864

Try Catch on HttpClient not working

$
0
0

why does HttpClient.GetAsync does throw exception when the server cannot be found? how can I handle this and tell the user that it cannot connect to the server. I tried adding the timeout but, it throws taskcancelexception (not sure if its the right word), but it give me "A task was canceled" exception error. If I used the timeout approach, I cannot tell if the server is down or it's just taking long to process the request.

btn1.Click += async (object sender, EventArgs e) =>
{
    try
    {
        using (var httpClient = new HttpClient())
        {
            var response = await httpClient .GetAsync("http://192.168.100.10:4200");
            if (response.IsSuccessStatusCode)
            {
                Toast.MakeText(this, "Works", ToastLength.Short).Show();
            }
            else
            {
                Toast.MakeText(this, response.StatusCode.ToString(), ToastLength.Short).Show();
            }
        }
    }
    catch (Exception ex)
    {
        Toast.MakeText(this, ex.GetBaseException().Message, ToastLength.Short).Show();
    }
};

Viewing all articles
Browse latest Browse all 89864

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>