简体   繁体   中英

Target Invocation Exception in async method

I am trying to retrieve items from an rss feed but at times I get a TargetInvocationException 'unable to connect to remote server'. I am trying to use a try catch block to catch this error but I am not managing as I need the variable feed to be used throughout the other code and like this it is not visible. Any suggestions?

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

 }
}

This kind of error cannot be prevented. It is an exogenous exception .

There is only one way to deal with those kinds of errors: your application must be designed to expect them and react in a reasonable way (eg, bring up an error dialog or notification).

In particular, don't try to ignore them with an empty catch block.

IAsyncOperationWithProgress<SyndicationFeed, RetrievalProgress> feed;

//Retrieve async the feeds..
try
{
   feed = await client.RetrieveFeedAsync(feedUri);
}
catch (TargetInvocationException e)
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM