Search code examples
c#.netwcfierrorhandler

Implementing WCF IErrorHandler for logging only


Probably trivial question.. I want to implement my own error handler to log errors and monitor what's going on. At this point I don't want to provide my own faults to the clients. I want it to be transparent - just like default WCF behavior. How should I implement ProvideFault to achieve this?

namespace IDATT.Web.Services
{
    using System;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Dispatcher;

    public class MyServiceErrorHandler : IErrorHandler 
    {
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            // ????
        }

        public bool HandleError(Exception error)
        {
            return true;
        }
    }
}

Solution

  • You can leave it empty. I do this to log errors to Elmah with no issues.

    EDIT

    I'm completely wrong on this. After looking at my implementation I do the following. As you can see, HandleError is the method that is basically empty and the logging takes place in ProvideFault.

    public class ElmahErrorHandler : IErrorHandler
    {
        public bool HandleError(Exception error)
        {
            return false;
        }
    
    
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            if (error == null)
            {
                return;
            }
    
            ErrorSignal.FromCurrentContext().Raise(error);
        }
    }
    

    Returning true in HandleError will make WCF think that no error occured. That means if you are just logging the error, this should always return false. If the error is not handled, ProvideFault is called and this is where you want to do the logging. You do not need to provide a fault Message.