title: Exception Logging for WCF Services using ELMAH
body: <p>We are using the excellent <a href="http://code.google.com/p/elmah" rel="noreferrer">ELMAH</a> to deal with unhandled exceptions in an ASP.NET 3.5 web application. This works extremely well for all of the site apart from WCF services which are being consumed using the REST features. When an exception occurs within the operation methods that is not handled by the application code, WCF handles it in various ways depending on the service contracts and configuration settings. This means that the exception does not end up firing the ASP.NET HttpApplication.Error event that <a href="http://code.google.com/p/elmah" rel="noreferrer">ELMAH</a> uses. The two solutions I am aware of to deal with this are:</p>
  
  <ul>
  <li>Wrap all method calls in a try { } catch(Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); throw; } to explicitly call Elmah within the catch block.</li>
  <li>Use <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx" rel="noreferrer">IErrorHandler</a> as described in <a href="http://will.hughesfamily.net.au/about/" rel="noreferrer">Will Hughes'</a> blog post <a href="http://will.hughesfamily.net.au/20090505/making-wcf-and-elmah-play-nice-together/" rel="noreferrer">Making WCF and ELMAH play nice together</a> to factor out the call to ELMAH to a separate ErrorHandler.</li>
  </ul>
  
  <p>The first option is extremely simple but is not exactly <a href="http://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself" rel="noreferrer">DRY</a>. The second option only requires you to decorate each service with the custom attribute after implementing the attribute and the ErrorHandler. I have done this based on <a href="http://will.hughesfamily.net.au/about/" rel="noreferrer">Will's</a> work but I want to verify that this is the <strong>correct approach</strong> before posting the code.</p>
  
  <p><strong>Is there a better way that I have missed?</strong></p>
  
  <p>The MSDN documenation for <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx" rel="noreferrer">IErrorHandler</a> says that the <strong>HandleError</strong> method is the place to do the logging but <a href="http://code.google.com/p/elmah" rel="noreferrer">ELMAH</a> accesses the HttpContext.Current.<strong>ApplicationInstance</strong>, which is null within this method even though HttpContext.Current is available. Making the call to Elmah within the ProvideFault method is a workaround as ApplicationInstance is set but this does not match the intent described in the API documentation. <strong>Am I missing something here?</strong> The documentation does state that you should not rely on the HandleError method being called on the operation thread which may be why ApplicationInstance is null in this scope.</p>