0

The below code posts an image to a Facebook page. However, when it fails (for whatever reason), it is not throwing any exceptions, so I cant find out the root cause of the failure (only a generic message that I provide ("Failed to post"). How would I alter the below code to show the actual error?

This is using the Facebook C# SDK

FacebookClient fbClient = new FacebookClient(accessToken);
fbClient.PostTaskAsync(path, post)
    .ContinueWith(task => 
    {
        if (!task.IsFaulted)
        {
            if (((IDictionary<string, object>)post).ContainsKey("scheduled_publish_time"))
            {
                DateTime dateTime = Utilities.ConvertUnixTimeStampToDateTime(Double.Parse((((dynamic)post).scheduled_publish_time)), true);
                OnFacebookPostSuccess("Successfully posted: (" +
                                dateTime + ") " + postText);
            }
            else
            {
                OnFacebookPostSuccess("Successfully posted: (" +
                                DateTime.Now + ") " + postText);
            }
        }
        else
        {
            OnFacebookPostFailed("Failed to post " + filename);
        }
    });

1 Answer 1

2

If it's writing "Failed to post" then you know the task has faulted. So you can find out the exception with the Task.Exception property. Note that that will give you an AggregateException, as it's possible that multiple things have gone wrong. (That may not be possible in your case, but it's possible in general with tasks.)

If you can use C# 5 instead, then you can use await which makes all of this much easier - the exception ends up being thrown at the point of the await expression when the task faults.

If you can't use C# 5, you might want to use the overloads of ContinueWith which specify task continuation options: you could attach one continuation just for the success case, and one continuation just for the failure case. You don't have to, but it can make things simpler if your failure handling is always the same.

2
  • Excellent, I did not know there was an Exception property in Task. Is it possible to split the AggregateException into multiple exceptions and determine where the error(s) are originating from? By the way, just started reading your book, bloody amazing stuff! (I feel star struck) Apr 30, 2013 at 6:12
  • 1
    @MarkGladstone: Absolutely - look at AggregateException.InnerExceptions. (It's very likely there'll only be in, mind you.)
    – Jon Skeet
    Apr 30, 2013 at 6:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.