XmlDocument.Load Error Handling

From one of the projects I have been working on, I came across a snippet of code that used the XmlDocument.Load method. What alarmed me about this piece of code was the fact that there was no error handling. If for some reason the XML file could not be found or a node was missing, the whole page would have crashed. Not good.

I must admit, I am not exactly the best person to speak about implementing wide-scale error handling in every facet of code. But I do ensure the core foundations of an application or website do incorporate sufficient error handling.

So back to the matter in hand. This is the original code using the XmlDocument.Load functionality:

XmlDocument doc = new XmlDocument();

doc.Load(Server.MapPath("/xml/storeGB.xml"));

XmlNode countryNode = doc.SelectSingleNode("//countries");
foreach (XmlNode node in countryNode.ChildNodes)
{
    //Do something with the elements
    Response.Write(node.Name + node.InnerText);
}

I changed the code to the following:

XmlDocument doc = new XmlDocument();

//Check if language XML file exists
if (File.Exists(Server.MapPath("/xml/storeGB.xml")))
{
    try
    {
        doc.Load(Server.MapPath("/xml/storeGB.xml"));

        XmlNode countryNode = doc.SelectSingleNode("//countries");

        if (countryNode != null)
        {
            foreach (XmlNode node in countryNode.ChildNodes)
            {
                //Do something with the elements
                Response.Write(node.Name + node.InnerText);
            }
        }
        else
        {
            //Output error message if there is no node
        }
    }
    catch (XmlException ex)
    {
        Debug.WriteLine(String.Format("XmlException for countries: {0}", ex.Message));
    }
}

I am sure you will agree that this is the better approach to using XmlDocument.Load.

String.Format In JavaScript

Whenever I work with strings whilst programming in .NET, somewhere along the lines I always find myself using the awesome “string.format”. I think all of you will admit its the most useful and easiest way to build up your strings.

The only downside to using the “string.format” method is that it lures you into a false sense of security and you find yourself lost without it when it comes to working with strings in other languages. This happened to me when I had to build up a long string in JavaScript. It was long and tedious…or maybe I am just lazy.

Luckily, there have been a few developers who extended the string object in JavaScript to include “string.format”. Amazing! Its goes along the lines of adding this to your own JavaScript code:

String.format = String.prototype.format = function() {
    var i=0;
    var string = (typeof(this) == “function” && !(i++)) ? arguments[0] : this;

    for (; i < arguments.length; i++)
        string = string.replace(/\{\d+?\}/, arguments[i]);

    return string;
}

Here are some other useful links I have found on how to implement “string.format” into your JavaScript code: