Using Exception.Data to add additional information to an Exception

Introduction

Whether you are writing a WinForms application or a complex .NET web site, you will invariably be catching exceptions, logging them and reporting them somewhere. (In this post, I’m not going to explain how to log exceptions). Simply reporting the exception as-thrown rarely captures enough information to be able to diagnose what happened. A FileNotFoundExceptionfor instance isn’t much use unless you know which file it was.

One way to deal with this issue is to wrap an exception up in a more explicit exception that includes the extra information, e.g.

string filename ... try { //... do something with the file } catch (FileNotFoundException ex) { CustomException ex2 = new CustomException("Missing cache: " + filename", ex); throw ex2; } 

This approach works but it leads to a lot of custom exceptions that are just extra work to create and maintain. Sometimes you’ll want a custom exception because you are going to handle it in a different way in some outer scope, but often you just want to log the error and redirect the user to an error page as there is nothing else you can do to fix the problem.

In cases like this, you can simplify things greatly by using the little-known .dataproperty on an Exception. This is an IDictionaryfor a “collection of key/value pairs that provide additional user-defined information about the exception” [MSDN].

Using this approach, you can write:

try { ... } catch (FileNotFoundException ex) { ex.Data.Add("cache filename", filename); throw; } 

Each surrounding scope can include a similar Try-Catchthat adds more information to .Dataso by the time you get to the top-most scope you have added a complete picture as to what might have caused the exception. And in doing so you haven’t lost any of the StackTrace information, nor have you wrapped the exception up needlessly in another exception.

At a higher level in your Global.asax file where you catch all unhandled exceptions, you can add even more to the .Data collection and perhaps includeall the interesting parameters on HttpContextlike RawUrl, cookies, …

ex.Data.Add("RawUrl", request.RawUrl); try { foreach (string cookieName in request.Cookies) { try { HttpCookie cookie = request.Cookies[cookieName]; string key = "Cookie " + cookie.Path + " " + cookieName; if (!ex.Data.Contains(key)) { ex.Data.Add(key, cookie.Value.ToString()); } } catch { // deliberately nothing in here, should // never happen, just being cautious } } // An extension method I use to spot bots - write your own ... if (request.IsABot()) { ex.Data.Add("BOT", "\*\*\*\*\*\*\*\*\*\*\*\*\* BOT 

*****************“); } ex.Data.Add(“UserAgent”, request.UserAgent); ex.Data.Add(“Referrer”, request.UrlReferrer); ex.Data.Add(“User Host”, request.UserHostName); } catch { // deliberately nothing in here, should never happen, just being cautious // but we definitely don’t want to cause // an exception while handling one! }

Exception Reporting Code

Now in your exception reporting code, you can write out the exception message and stack trace followed by a dump of all the key value pairs in .Data. I tend to use log4net on each server writing to a rolling log file and SQL server to capture the exception data centrally. For SQL, you’ll probably want one table for the Exception itself and another table with a row for each key/value pair in .Data.

Comments

One cause of Exceptions on web servers is bots and client-side ‘web accelerators’. Both of these can hit pages with incorrect or outdated parameters that you simply didn’t expect to receive. That’s why I add a BOT warning on every exception as the exception itself may seem severe but in reality it’s benign and no user has ever seen it. I even found one antivirus product that takes each request you make and sends the URL to Japan where another server makes a second request back to check the page for viruses! It even pretends not to be a Bot in the UserAgent and of course, all your ‘security- through-obscurity’ URLs are now sitting on a server in Japan, but you know security through obscurity is no security at all, right?

Another browser add on called FunWebProducts would routinely corrupt Viewstate information so if you see that in your exceptions log, you know who to blame.



Mon Mar 08 2010 07:15:05 GMT-0800 (Pacific Standard Time)



Disqus goes here