Pages

Thursday, June 28, 2012

No ELMAH, forget about it!

If you haven't heard of ELMAH you need to check out the following links pronto!

ELMAH - Home
Scott Hanselman on ELMAH

I highly recommend using ELMAH whenever you can when developing custom applications. There are very few things that you can "bolt-on" to your application that will provide so much functionality with so little effort.

But what happens when you can't use ELMAH? If for some reason you can't use ELMAH in your application (like, for say... you work with an old school architect who just doesn't get it, and doesn't want to try to get it) then what do you do? What you do is forget about it, and write your own!

Error handling modules are extremely simple, and so very easy to add to an existing .Net application. All that you need to do to create an error handling module is to create a new class that inherits from IHttpModule and register your new module in your applications web.config.

Here is an example error handling module class:

namespace Web.ErrorHandling
{
    public class ErrorHandlingModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
            //clean-up code here.
        }

        public void Init(HttpApplication context)
        {
            if (context != null)
                context.Error += new EventHandler(OnError);
        }

        #endregion

        #region Event Handlers

        public void OnError(object source, EventArgs e)
        {
            Exception ex = HttpContext.Current.Server.GetLastError();

            if (ex == null)
                return;

            ErrorHandler.LogException(ex);
        }
    }
}


In this example I am calling an existing error handling class (ErrorHandler.LogException) that I already had in my project, but you can do whatever is appropriate for you your app.

Once you've finished writing your class, all you have to do is register the class in your applications web.configsection:

<httpModules>
      <add name="ErrorModule" type="Web.ErrorHandling.ErrorHandlingModule, Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31ecffd9ef3ffd3e" />
</httpModules>


And viola! You have ELMAH like error capturing capability in your app. Forget about it!

No comments:

Post a Comment