I’ve found myself writing code like this quite a bit lately:

var orderElement 
    = document.Element(OrderXml.OrderElementName);
if (orderElement == null)
{
    var message
        = string.Format(
            "Didn't find expected child element <{0}>",
            OrderXml.OrderElementName);
    throw new InvalidOperationException(message);
}

The intent is to find a specified child element, throwing an error if the element is not found.

After writing the same error checking code one or two times too many, I wrote some extension methods to make the task simpler. With the extension method RequiredElement, the above code simplifies quite a lot:

var orderElement 
    = document.RequiredElement(OrderXml.OrderElementName);

Here’s the definition for RequiredElement - as you can see, the only significant difference is in the type of exception thrown.

public static XElement RequiredElement(
    this XElement parent, 
    XName child)
{
    parent.MustNotBeNull(
        "parent",
        "Parent element must not be null");
    var result = parent.Element(child);
    if (result == null)
    {
        throw new XmlFormatException(
            parent,
            string.Format(
                "Didn't find required child element {0}", 
                child.LocalName));
    }

    return result;
}

The related extension methods, RequiredAtribute and RequiredElements (plural) - included in the attachment - are entirely similar.

XmlFormatException is a pretty vanilla custom exception type, except for the detail of taking an Xelement as one of the parameters to its constructors - this is promptly case to IXmlLineInfo allowing the exception to properly report the location within the Xml file where the problem was detected, useful for other developers and for end users trying to solve a problem.

Comments

blog comments powered by Disqus
Next Post
NAntGraph v2.2 Released  16 Jun 2010
Prior Post
Vending Machine UX Fail  30 May 2010
Related Posts
Prefer declarative method names  03 Feb 2018
Using Premeditation  27 Jan 2018
With Relocation  20 Jan 2018
Using Consolidation  13 Jan 2018
Using Semantic Types  06 Jan 2018
Using Extension Methods  30 Dec 2017
Error Methods  25 Nov 2017
Pass implementations, not representations  14 Oct 2017
Avoiding the Singleton Pattern  22 Jul 2017
Implementing the Singleton Pattern  15 Jul 2017
More smart-code posts »
Related Pages
June 2010 archive