我正在使用Xamarin.Forms创建一个安卓应用程序。在频繁地切换互联网连接时,我得到了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。感谢所有反馈意见。
谢谢!
发布于 2018-04-05 21:05:06
我也看到这个了。我通过以下方法成功地捕获了它:
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);
}
...
}https://stackoverflow.com/questions/47609122
复制相似问题