无法通过委托传递错误

时间:2012-11-23 16:12:00

标签: c# .net

无法通过委托传递错误...

错误:

Object reference not set to an instance of an object.

CODE:

 RssReader.GetRssItems(IsUsePlainText,
                                  url, ShowImages,
                                  items =>
                                  {
                                      if (items.Any())
                                      {
                                          DataRSS.AddRange(items);
                                      }
                                  }, error => {

                                      var s = error.Message; // Nothing is go here... :(
                                  }
                                            , OnFinally);



public static void GetRssItems(bool isUsePlainText, string rssFeedUrl, bool showImages, 
            Action<IEnumerable<RssFeedItem>> onGetRssItemsCompleted = null,
            Action<Exception> onError = null, Action onFinally = null)
{

  var webClient = new WebClient();

  webClient.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
  {
     try
     {
        if (e.Error != null) // report error
        {
            if (onError != null)
            {
                 onError(e.Error);
            }
            return;
         }

         var stream = e.Result;
         var response = XmlReader.Create(stream); 
         var feeds = SyndicationFeed.Load(response); // When something is wrong here an exception occurs

         // do other stuff...

}
 catch (Exception ex)
 {
   onError(ex); // ERROR HAPPENS HERE.... "Object reference not set to an instance of an object."
   return;

 }
 finally
 {
   if (onFinally != null)
   {
      onFinally();
   }
}

更新:

enter image description here

2 个答案:

答案 0 :(得分:2)

听起来onError为空。

更改为:

if (onError != null) onError(ex);

或者,如果调用者未能传入委托,则执行其他操作。

答案 1 :(得分:2)

执行与第一次调用操作时相同的空检查:

catch (Exception ex)
 { 
    if (onError != null)
        onError(ex); 
   return;    
 }

如果您想避免空检查 - 在方法顶部将虚拟处理程序附加到Action委托:

onError += (e) => {};