HandleError and ELMAH

ELMAH is a very-very nice exception reporting tool for ASP .NET websites. It is implemented as an http module. It supports exceptions’ mailing, logging to a database, a file, access exceptions via *.axd handler and many many other things. ELMAH logs all unhandled exception until you filter them in a configuration file. Even it will log an exception if custom errors are enabled. But this is only in case if you work with classic ASP .NET WebForms. When you have a deal with MVC and HttpError attribute to handle errors and show custom error messages, exceptions become handled by MVC, but not by ASP and ELMAH has no idea about them.    To fix that you need to raise a logging by yourself in code. You need inherit from HttpErrorAttribute and override OnException method to call ELMAH’s API ErrorSignal.FromContext(HttpContext).Raise(Exception, HttpContext). Check this example below:

public class HandleErrorWithElmahAttribute : HandleErrorAttribute { protected override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); var httpContext = filterContext.HttpContext; if (!filterContext.ExceptionHandled) return; ForceElmahNotification(filterContext.Exception); } private static void ForceElmahNotification(Exception exception) { var context = System.Web.HttpContext.Current; if (context == null) return; var signal = ErrorSignal.FromContext(context); if (signal != null) signal.Raise(exception, context); } }
This entry was posted in .NET, ASP .NET MVC, ELMAH. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s