1

On our UAT environment, I am getting an exception on certain page types with a stacktrace pointing to a specific class and line number. The problem, is that the line in question should not be able to throw an exception.

Here is the code:

    foreach (var child in children) //children is of type List<Item>
    {
      var dataItemIdValue = child["DataField"];
      var pageItemIdValue = child["PageField"];
      ID dataItemId;
      ID pageItemId;
      if (ID.TryParse(dataItemIdValue, out dataItemId) && ID.TryParse(pageItemIdValue, out pageItemId)) //<<<this is the line which the stacktrace is showing as the root of the exception
      {
        var dataItem = contextItem.Database.GetItem(dataItemId);
        var pageItem = contextItem.Database.GetItem(pageItemId);

        if (!result.ContainsKey(dataItem.ID))
        {
          result.Add(dataItem.ID, pageItem);
        }

        if (!result.ContainsKey(pageItem.ID))
        {
          result.Add(pageItem.ID, dataItem);
        }
      }
    }

So according to the stack trace information an exception has been raised during the call to ID.TryParse, however, this method should never throw an exception.

What techniques can I use to debug this further (I have not been able to recreate the issue locally) and in what ways could the exception stack trace be misleading me?

2

I do agree, I think you are being misled. However I also strongly believe you should not be second guessing how Sitecore stores its field information and parse it yourself. It would be both safer and cleaner if your code looked something like this:

    foreach (var child in children) //children is of type List<Item>
    {
      var dataItemField = (ReferenceField)child.Fields["DataField"];
      var pageItemField = (ReferenceField)child.Fields["PageField"];
      
      if (dataItemField?.TargetID != ID.Null && pageItemField?.TargetID != ID.Null)
      {
        var dataItem = dataItemField.TargetItem;
        var pageItem = pageItemField.TargetItem;

        if (!result.ContainsKey(dataItem.ID))
        {
          result.Add(dataItem.ID, pageItem);
        }

        if (!result.ContainsKey(pageItem.ID))
        {
          result.Add(pageItem.ID, dataItem);
        }
      }
    }

It's cleaner to use the built-in API for operations such as this, rather than just grabbing the raw string value and get to work on it. It often leads, as you've found, to strange situations.

You don't need to check .TargetItem for null in this case. .TargetID will have already done that.

1
  • Good tip - also more concise code, which I like! Dec 30 '20 at 23:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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