Thursday, 21 October 2010

C#: Capture exception and all inner exceptions


With complex architectures and many layers in the code throwing exceptions, it can prove difficult to find out exactly what went wrong.

Generally, the GUI may produce an error for example "Payment could not be processed." when making a payment on-line. From this error, we don't know which layer caused this error, but we know that along the way, something occurred.

This code snippet takes an exception and loops through all inner exceptions and produces a string for the whole exception. This can be stored in a logfile and the problem can be easily identified.


/// <summary>
/// Gets a full exception message string from a given exception.
/// This will loop through all inner exceptions.
/// </summary>
/// <param name="ex">Incoming exception</param>
/// <returns>Full exception message</returns>
internal string GetFullExceptionMessage(Exception ex)
{
    string result = string.Empty;
 
    while (ex != null)
    {
    result += ex.ToString() + Environment.NewLine;
    ex = ex.InnerException;
    }
 
    return result;
}

No comments: