March 2, 2017

An Exception Handling String Formatter

A string extension class to safely use string.Format().
public static class StringExtensions
{
    // Safe format, capture any Format Exceptions.
    public static string TryFormat(
        this string formatText,
        params object[] parameters)
    {
        string res = "";
        try
        {
            res = string.Format(formatText, parameters);
        }
        catch (FormatException fe)
        {
            string msg = "Formatting string error : formatText=" + formatText + 
                                ", parameters=\'" +
                              string.Join( ",", parameters ) + "\', exception=" + fe;
            Trace.WriteLine("string.Format code needs fixing - " msg);
            res = formatText;
            Debug.Assert(false, msg);
        }
        return res;
    }
}
I have seen this method take down a complete application because too few parameters were passed.

No comments: