When something goes wrong in a .NET application, it’s important to log sufficient information from the exception for diagnostic purposes. Here are some ideas on how to do this well.

Under pressure to deliver working code, I find it very tempting to throw a token piece of logging into place and then to move on:

try
{
    // ...
}
catch (Exception ex)
{
    Log.Error("{0} ({1})", ex.Message, ex.GetType().Name);
}

The problem with this approach is that is discards information; when used correctly, a .NET exception includes a great deal of information useful for diagnostic purposes.

The first improvement is to recognise that it’s common for some frameworks to wrap exceptions to supply context to the error. We need to be checking the InnerException and handling this wrapping.

Since we don’t want to write the same code over and over, let’s wrap this into an extension method:

/// <summary>
/// Turn a single exception into a sequence by flattening the nested inner exceptions
/// </summary>
/// <param name="exception"></param>
/// <returns>A sequence of all the exceptions.</returns>
public static IEnumerable<Exception> AsEnumerable(this Exception exception)
{
    var e = exception;
    do
    {
        yield return e;
        e = e.InnerException;
    } while (e != null);
}

Catching and logging an exception now looks like this:

try
{
    // ...
}
catch (Exception ex)
{
    foreach (var e in ex.AsEnumerable())
    {
        Log.Error("{0} ({1})", ex.Message, ex.GetType().Name);
    }
}

This is an improvement - but we can do better.

Every exception contains a dictionary of name/object values - we should include those in our output. ADO.NET, for example, includes details about the database connection, server version and the SQL being executed in every exception.

Again, we don’t want to write the same code over and over, so let’s create a new extension method:

/// <summary>
/// Turn a single exception into a sequence of strings for logging
/// </summary>
/// <param name="exception"></param>
/// <returns>A sequence of strings</returns>
public static IEnumerable<string> AsStrings(this Exception exception)
{
    yield return string.Format("{0} ({1})", 
       exception.Message, exception.GetType().Name);

    if (exception.Data != null)
    {
        foreach (DictionaryEntry p in exception.Data)
        {
            yield return string.Format("  {0}: {1}", p.Key, p.Value);
        }
    }
}

With this method, we get all the detail (if any) out of the dictionary of values.

Combine the two methods together and we get the following:

try
{
    // ...
}
catch (Exception ex)
{
    foreach (var s in ex.AsEnumerable().SelectMany(e => e.AsStrings()))
    {
        Log.Error(s);
    }
}

For bonus credit, extend the logging framework so that we can write this:

try
{
    // ...
}
catch (Exception ex)
{
    Log.Exception(ex);
}

With the implementation of Log.Exception left as an exercise for the reader.

Comments

blog comments powered by Disqus
Next Post
Why Monospaced Fonts?  24 Jan 2016
Prior Post
SharpDox Tips  02 Jan 2016
Related Posts
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
When are you done?  18 Apr 2022
Fixing GitHub Authentication  28 Nov 2021
Archives
January 2016
2016