Xamarin表单System.Net.WebException

时间:2017-12-02 14:51:00

标签: c# exception-handling xamarin.forms system.net.webexception

我正在使用Xamarin.Forms创建一个Android应用程序。 在经常关闭和打开互联网连接时,我得到 System.Net.WebException ConnectFailure 异常。我试图在我的PCL代码中处理它,但它没有陷入其中。 以下是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);
        }
    }

有人可以指导我如何在给定的catch块中处理WebException。感谢所有反馈意见。

谢谢!

1 个答案:

答案 0 :(得分:1)

我也看到了这一点。我设法通过使用:

来捕获它
catch (System.Net.WebException ex) {}

出于某种原因,即使我试图重新抛出它,它也不会冒泡我并停止执行;但是我可以强制它冒泡并最终通过重新包装异常来处理它。

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);
   }
   ...
}