Add Additional Information to Your Exceptions


When Enterprise Library was called Microsoft Application Blocks, if you wanted to log an Exception, you would write (assuming “ex” is an Exception):

ExceptionManager.Publish(ex)

And if you wanted to log some extended properties you could do something like this:

NameValueCollection customerInfo = new NameValueCollection();
customerInfo.Add("name","scott");
customerInfo.Add("email","blah@blah.com");
ExceptionManager.Publish(ex,customerInfo); 

Now that I am upgrading all legacy code to Enterprise Library 2006 for .NET 2.0, I couldn’t find a way to do this since the only way to log an error is:

ExceptionPolicy.HandleException(ex, "General Policy");

where “General Policy” is the name of the Exception Policy in the config file telling the Block what to do with the exception.

Looking in the config file, I noticed a formatter template with the following at the tail end of the template attribute, “…Extended Properties: {dictionary({key} – {value} )}”.  The formatter template is used to format the exception that is about to be logged somewhere.  Looking through the code for where it loops through this Dictionary, I noticed it accessing an IDictionary of Exception.Data.  Exception.Data?  Where did that come from?

Data is a new .NET framework 2.0 property of the Exception class to allow you to add any user-defined information about the exception.  Nothing more to it:  Just a simple name/value dictionary for your enjoyment.  As if you couldn’t figure it out, my new code would look like:

ex.Data.Add("name","scott");
ex.Data.Add("email","blah@blah.com");
ExceptionPolicy.HandleException(ex, "General Policy");

And as long as you use the default formatter, it will log this data at the end of the FormattedException field.


Leave a Reply

Your email address will not be published. Required fields are marked *