Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
        }
    }
}
like image 340
katit Avatar asked Jun 13 '12 20:06

katit


2 Answers

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.

like image 184
cadrell0 Avatar answered Sep 28 '22 23:09

cadrell0


From the documentation (http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx):

Implement the HandleError method to ensure error-related behaviors, including error logging, assuring a fail fast, shutting down the application, and so on.

Also the link above notes that only HandleError is called after the response has been sent back to the client. So be nice to your client (don't make them wait while you log), leave ProvideFault blank and perform logging operations in HandleError.

like image 26
Tron5000 Avatar answered Sep 28 '22 23:09

Tron5000