Target Invocation Exception in async method

1.2k Views Asked by At

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

 }
}
2

There are 2 best solutions below

2
On
IAsyncOperationWithProgress<SyndicationFeed, RetrievalProgress> feed;

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

}
2
On

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 (e.g., bring up an error dialog or notification).

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