Skip to content

DLaB.Xrm.Exceptions

Daryl LaBar edited this page Jun 28, 2019 · 2 revisions

Some exceptions to help simplify some come error scenarios.

EnumCaseUndefinedException<TEnum>

An exception that is thrown when a switch statement has been defined for an Enum, but the actual value has not been defined as a case. This helps safe guard against switch statements that aren't updated when a new value is added to the enum.

switch (account.AccountCategoryCodeEnum.GetValueOrDefault())
{
    case Account_AccountCategoryCode.PreferredCustomer:
        ScheduleCall();
        break;
    case Account_AccountCategoryCode.Standard:
        SendMail();
        break;
    default:
        throw new EnumCaseUndefinedException<Account_AccountCategoryCode>(account.AccountCategoryCodeEnum.GetValueOrDefault());
}

The error message is returned follows the following format:

No case statement for Xyz.Xrm.Entities.Account_AccountCategoryCode.{EnumStringValue} ({EnumIntegerValue}) has been defined.

InvalidPluginStepRegistrationException

The exception that is thrown when a Pre/Post Image or attribute on the image isn't registered for the plugin. It is mostly used by extension methods of the plugin context:

public static void AssertEntityImageRegistered(this IPluginExecutionContext context, string imageName)
{
    var pre = context.PreEntityImages.ContainsKey(imageName);
    var post =  context.PostEntityImages.ContainsKey(imageName);

    if (pre && post)
    {
        throw new Exception($"Both Preimage and Post Image Contain the Image \"{imageName}\".  Unable to determine what entity collection to search for the given attributes.");
    }

    if (!pre && !post)
    {
        throw InvalidPluginStepRegistrationException.ImageMissing(imageName);
    }
}

#endregion AssertEntityImageRegistered

MissingAttributeException

The exception that is thrown when an Entity is expected to contain an Attribute, but the attribute isn't found. It is mostly used by extension method of entity:

/// <summary>
/// Checks to see if the Entity Contains the attribute names, and the value is not null.
/// Any missing/null attributes will result in an exception, listing the missing attributes.
/// </summary>
/// <param name="entity"></param>
/// <param name="attributeNames"></param>
/// <returns></returns>
public static void AssertContainsAllNonNull(this Entity entity, params string[] attributeNames)
{
    if (entity.ContainsAllNonNull(out List<string> missingAttributes, attributeNames)) { return; }

    if (missingAttributes.Count == 1)
    {
        throw new MissingAttributeException("Missing Required Field: " + missingAttributes[0]);
    }

    throw new MissingAttributeException("Missing Required Fields: " + missingAttributes.ToCsv());
}