Thursday, March 22, 2012

Using ELMAH with Custom Errors turned on

This article specifically addresses handling uncaught exceptions in your web application. ELMAH can be plugged in pretty quickly with almost all of your changes happening in your web.config and global.asax.cs files.

Here is a slimmed down web.config file. When a 404 error occurs, it will not be logged to Elmah and the user will be redirected to a custom "Not Found" page. All other exceptions will be logged by Elmah and the user is redirected to a custom error page. To view the list of logged exceptions, the url is http://(yoursite)/elmah.axd (note that elmah.axd does not physically exist anywhere). Also, IIS will deny users that are not part of the "Developers" group to see the log page.
<?xml version="1.0"?>
<configuration>
  
  <configSections>
    <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah"/>
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
    </sectionGroup>
  </configSections>

  <elmah>
    <security allowRemoteAccess="yes" />
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="Elmah" />
    <errorFilter>
      <test>
        <or>
          <equal binding="HttpStatusCode" value="404" type="Int32" />
          <regex binding="BaseException.Message" pattern="The file '/[^']+' does not exist" />
        </or>
      </test>
    </errorFilter>
  </elmah>
  
  <system.web>
    <customErrors mode="On" defaultRedirect="~/Home/Error">
      <error statusCode="404" redirect="/Home/NotFound" />
    </customErrors>
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah"/>
    </httpModules>
      <httpHandlers>
        <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
      </httpHandlers>
  </system.web>

  <location path="elmah.axd">
    <system.web>
      <authorization>
        <allow roles="Developers"/>
        <deny users="*" />
      </authorization>
    </system.web>
  </location>

</configuration>


In global.asax.cs I commented out the filter for the HandleErrorAttribute so that Elmah would handle the exceptions.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    // Commented out so that web.config can have customErrors="true" and still let Elmah handle exceptions
    //filters.Add(new HandleErrorAttribute());
}


So now when I bring up my elmah.axd page I don't see 404 errors when the browser is looking for the favicon.ico file which I was seeing a lot of previously.

No comments:

Post a Comment