Mar 1, 2012

WCF error handling by implementing IErrorHandler

By implementing IErrorHandler you can control the fault message which is sent to the caller and perform error processing such as logging
  

 public class MyCustomeErrorHandler : IErrorHandler
    {

        public bool HandleError(Exception error)
        {
            Trace.TraceError(error.ToString());
            return true;
        }

        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
   //Log server error for troubleshooting error
   
   //you can customise fault exception as you want
            FaultException faultException = new FaultException("Server error encountered.);
            MessageFault messageFault = faultException.CreateMessageFault();
            fault = Message.CreateMessage(version, messageFault, faultException.Action);
        }

    }
We can now add this to ServiceBehavior
  

 public class MyCustomeErrorHandlerServiceBehavior : Attribute,IServiceBehavior
    {
        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase){}

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection endpoints, BindingParameterCollection bindingParameters){}

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            IErrorHandler handler = new MyCustomeErrorHandler();
            foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
            {
                dispatcher.ErrorHandlers.Add(handler);
            }
        }
    }
 
Now this way your custome error handler will be used where you can put some friendly message which will be sent to the caller.

The other way is to catch your application error in your operation and then throw FaultException somethign like this
 

 public string GetData(int value)
 {
  try
  {
   throw new Exception("My Service Operation Error");
  }
  catch (Exception ex)
  {
   //Log your applocation exception
   throw new FaultException(new ApplicationException("My Custome Fault Messahe"),new FaultReason("some fault reason"));
  }
 }

No comments:

Post a Comment