Friday, September 11, 2009 #

Quick Extension Method for Grabbing Exception.Data

Technorati Tags:

This is nothing spectacular and exception methods are used all the time.  But thought to just post up for those of you who haven’t used them a lot.  Today I needed to check that Exception.Data is null.  If it was not, I wanted to then send a string. 

First I added the data to the exception which is just the SOAP text that was sent via the HttpRequest that was used in a method that I called:

XmlDocument doc = new XmlDocument();
doc = CreateRequestXML();
 
// Grab the SOAP that is being sent for possible logging later
_SOAPSent = doc.OuterXml;
 
....
try{ ....}
catch (Exception ex)
{
    // include SOAP string that was sent
    ex.Data.Add(Constants.SoapRequestData, _SOAPSent);
 
    throw;
}

And I ended up just creating an extension method to handle checking for that value and if it’s null, and returning the string back without error if the data key is not available:

namespace [CompanyName].[ProjectName].Extensions.ExceptionExtensions
{
 
    public static class ExceptionExtensions
    {
        /// <summary>
        /// Gets the exception data.  If no data exists returns empty string
        /// </summary>
        /// <param name="ex">The ex.</param>
        /// <param name="key">The key.</param>
        /// <returns>Data retrieved from Exception.Data</returns>
        static public string GetExceptionData(this Exception ex, string key)
        {
            if (ex.Data != null && ex.Data.Contains(key))
                return ex.Data[key].ToString();
            else
                return string.Empty;
        }
    }
}

Now I can use it like this when I want to safely retrieve the data:

catch (Exception ex)
{
    string soapcalled = ex.GetExceptionData(Constants.SoapRequestData);
    service.LogFailure(..., ..., ..., soapcalled);
}

I used a string constant as the key to prevent magic strings being specified as a param.


posted @ Friday, September 11, 2009 4:45 PM | Feedback (0)