DEV Community

tackme
tackme

Posted on • Edited on

Sitecore sometimes doesn't throw an exception when item creation fails

In Sitecore, you would use the Item.Add(string name, TemplateID templateID, ID newItemID) method to create an item. This method has a strange behavior when item creation fails.

There are three causes of failure:

  1. An inexistent template is specified.
  2. An invalid item name is specified.
  3. A context user has no creation rights.

In those cases, only the first one is when the method returns null without throwing an exception. See the next examples.

var home = Context.Database.GetItem("/sitecore/content/Home");

// An inexistent template is specified
home.Add("case1", new TemplateID(ItemIDs.Undefined)); // => null

// An invalid item name is specified
home.Add("case/2", new TemplateID(TemplateIDs.Folder)); // => InvalidItemNameException

// A context user has no creation rights
var user = User.FromName("sitecore\\access denied user", isAuthenticated: true);
using (new UserSwitcher(user))
{
    home.Access.CanCreate(); // => false
    home.Add("case3", new TemplateID(TemplateIDs.Folder)); // => AccessDeniedException
}
Enter fullscreen mode Exit fullscreen mode

Furthermore, one more unusual behavior appears when supplying null to argument. We typically expect the method to throw the ArgumentNullException in that case. But it returns null when specifying ID.Null to the newItemID argument.

var home = Context.Database.GetItem("/sitecore/content/Home");

// Specify null to item name
home.Add(null, new TemplateID(TemplateIDs.Folder)); // => ArgumentException

// Specify null to template ID
home.Add("test", null, ID.NewID); // => ArgumentNullException

// Specify null to item ID
home.Add("test", new TemplateID(TemplateIDs.Folder), null); // => ArgumentNullException

// Specify ID.Null to item ID
home.Add("test", new TemplateID(TemplateIDs.Folder), ID.Null); // => null
Enter fullscreen mode Exit fullscreen mode

This result is due to be used Assert.ArgumentNotNull instead of Error.AssertID for the argument assertion.

In conclusion, it goes without saying, we must not only handle an exception thrown but also check whether the return value is null.

Thank you.

Top comments (0)