Andrew Wilinski

HandleErrorAttribute and Health Monitoring

I'm a big fan of the ASP.NET Health Monitoring features that were released in version 2.0. I specifically like the fact that errors can be emailed and logged for later viewing. Our company stores the error messages in SQL Server which we use as error tracking to find which errors were fixed, when they were fixed, and who fixed them.

While we were tackling the issue of error handling and custom error pages we discovered that the HandleErrorAttribute does not invoke any of the Health Monitoring features. This was a requirement for our project and forced us to find a way to work around the issue. This spawned the HandleErrorHmAttribute.

The attribute itself was very easy to create by inheriting all of the features from the ASP.NET MVC HandleErrorAttribute. The thing that proved to be tricky was raising the System.Web.Management.WebRequestErrorEvent. When we looked at the WebRequestErrorEvent we noticed it did not have any public constructors. I don't know why Microsoft implemented the events this way. The workaround is to create a new WebRequestErrorEventMvc inherited from WebRequestErrorEvent with public constructors.

   1: using System;
   2: using System.Web.Management;
   4: public class WebRequestErrorEventMvc : WebRequestErrorEvent {
   5:     public WebRequestErrorEventMvc(string message, object eventSource, int eventCode, Exception exception) : base(message, eventSource, eventCode, exception) {}
   6:     public WebRequestErrorEventMvc(string message, object eventSource, int eventCode, int eventDetailCode, Exception exception) : base(message, eventSource, eventCode, eventDetailCode, exception) {}
   7: }

Now that we have an event that we can instantiate and raise, we turn to the HandleErrorHmAttribute. All that has to be done is derive from the System.Web.Mvc.HandleErrorAttribute, override the OnExcpetion method, call the base method and raise the WebRequestErrorEventMvc.

   1: using System.Web.Mvc;
   3: public class HandleErrorHmAttribute : HandelErrorAttribute {
   4:     public override void OnException(ExceptionContext context)
   5:     {
   6:         base.OnException(context);
   7:         new WebRequestErrorEventMvc("An unhandled exception has occurred.", this, 103005, context.Exception).Raise();
   8:     }
   9: }

There you have it. Just use the HandleErrorHmAttribute the same way you use the System.Web.Mvc.HandleErrorAttribute. Now, everytime an error occurs, Health Monitoring works just like it did in ASP.NET.


No Comments