Xamarin Forms System.Net.WebException

706 Views Asked by At

I am creating an android app using Xamarin.Forms. On toggling internet connectivity off and on frequently, i am getting System.Net.WebException ConnectFailure exception. I have tried to handle it in my PCL code but it is not getting caught in there. Following is the sample code of shared project of Xamarin.Forms.

 public async Task GetNewSomething(CancellationToken token)
    {
          await Task.Run(async () =>
            {
                while (true)
                {
                    token.ThrowIfCancellationRequested();
                    await Task.Delay(10000, token);
                    if (CrossConnectivity.Current.IsConnected) // check if internet is available
                    {
                        try
                        {   
                            //Make server call to get data
                            FacilityManager.GetAllFacilities(list =>
                            {
                              //For testing purpose : Intentionally thowing an exception to check if we can catch it in the catch block below.  
                                throw new WebException();
                                MessagingCenter.Send(list, "FreshFacilityListFromServer");
                            }, 0, true);
                        }
                        catch (WebException ex)
                        {
                       //It is never gets caught here. :(
                        }
                    }
                }
            }, token);
        }
    }

Can someone please guide me how can i handle WebException in the given catch block. Appreciate all feedback's.

Thanks!

1

There are 1 best solutions below

0
On

I'm seeing this too. I managed to catch it by using:

catch (System.Net.WebException ex) {}

For some reason, it is not bubbling for me and halting execution even when i try to re-throw it; however i'm able to force it to bubble and eventually handle it by rewrapping the exception.

public async Task DownloadAndInstall(...)
{
  ...

  // Download
  try
   {
      await Download(...)
   }
   catch (Exception ex)
   {
       throw new DownloadException("Something bad happened");
   }
   ...
}

public async Task Download(...)
{
   ...
   // try some web activity
   try
   {
      ...
   }
   catch (System.Net.WebException ex)
   {
      throw new Exception("Uncaught exception", ex);
   }
   ...
}