【问题标题】:Xamarin Forms System.Net.WebExceptionXamarin 窗体 System.Net.WebException
【发布时间】:2017-12-02 14:51:00
【问题描述】:

我正在使用 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。感谢所有反馈。

谢谢!

【问题讨论】:

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


    【解决方案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);
       }
       ...
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-25
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2017-12-01
      • 2017-11-11
      • 2017-05-08
      相关资源
      最近更新 更多