我正在尝试从rss提要中检索项目,但有时我得到一个TargetInvocationException“无法连接到远程服务器”。我试图使用try catch块来捕获此错误,但我没有管理,因为我需要在整个其他代码中使用变量feed并且像这样它是不可见的。有什么建议吗?
public static async Task<List<FeedItem>> getFeedsAsync(string url)
{
//The web object that will retrieve our feeds..
SyndicationClient client = new SyndicationClient();
//The URL of our feeds..
Uri feedUri = new Uri(url);
//Retrieve async the feeds..
try
{
var feed = await client.RetrieveFeedAsync(feedUri);
}
catch (TargetInvocationException e)
{
}
//The list of our feeds..
List<FeedItem> feedData = new List<FeedItem>();
//Fill up the list with each feed content..
foreach (SyndicationItem item in feed.Items)
{
FeedItem feedItem = new FeedItem();
feedItem.Content = item.Summary.Text;
feedItem.Link = item.Links[0].Uri;
feedItem.PubDate = item.PublishedDate.DateTime;
feedItem.Title = item.Title.Text;
try
{
feedItem.Author = item.Authors[0].Name;
}
catch(ArgumentException)
{ }
feedData.Add(feedItem);
}
return feedData;
}
}
}
答案 0 :(得分:1)
无法阻止此类错误。这是一个exogenous exception。
只有一种方法可以处理这类错误:您的应用程序必须设计为期望它们并以合理的方式做出反应(例如,调出错误对话框或通知)。
特别是,请勿尝试使用空catch
块来忽略它们。
答案 1 :(得分:0)
IAsyncOperationWithProgress<SyndicationFeed, RetrievalProgress> feed;
//Retrieve async the feeds..
try
{
feed = await client.RetrieveFeedAsync(feedUri);
}
catch (TargetInvocationException e)
{
}