Search code examples
c#asp.neterror-handlingelmah

Catching an exception and clearing it before ELMAH gets it


I have a problem where I have an exception being thrown that I am capturing in Global.asax. As part of this exception handling I redirect the user to a specific page because of this exception.

I also have ELMAH error handling with the email module plugged in. I do not want to receive emails for this exception. I also don't want to add this type of exception to ELMAHs ignore list, in case I want to do granular work around the exception (i.e., only if it matches certain properties, happens on certain pages)

I want to:

  • write an Application_OnError that redirects a user to a page (I know how to do this part, more for procedure I've left it here)
  • in the Application_OnError stop ELMAH from receiving this error after I've caught it

I am currently calling Server.ClearError() inside my App_OnError method, but am still receiving these emails.


Solution

  • As per the ELMAH documentation

    I put leave my Application_OnError method in my Global.asax but I also add the following global methods:

    void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs args)
    {
        Filter(args);
    }
    
    void ErrorMail_Filtering(object sender, ExceptionFilterEventArgs args)
    {
        Filter(args);
    }
    
    void Filter(ExceptionFilterEventArgs args)
    {
        if (args.Exception.GetBaseException() is HttpRequestValidationException)
        {
            args.Dismiss();
        }
    }
    

    What this does is dismiss the ELMAH exception if it is the type that matches what I want - in my case the HttpRequestValidationException.

    The ErrorMail_Filtering method is only required if you have the error mail filter turned on - which I do.