다음을 통해 공유


Implementing IErrorHandler

We currently have a sample that illustrates how to create an IErrorHandler to provide error logging. This sample is called ErrorLogging and it is located in the following directory in the WCF/WF samples: WF_WCF_Samples\WCF\Extensibility\ErrorHandling. You can find the documentation page for this sample here: http://msdn.microsoft.com/en-us/library/ms751439(VS.90).aspx.  This sample overloads the IErrorHandler.HandleError method to write error information to a log file. IErrorHandler also defines a method called ProvideFault which allows you to determine the fault object the service will return to the client. Keep in mind that any object returned to the client should be a data contract type. This is requried so a non-.NET client will be able to deserialize the object. In the ProvideFault method you can inspect the actual exception using the error parameter and create an appropriate fault. Here is a simple implementation that checks for a DivideByZeroException and returns a MathFault:

 public void ProvideFault(Exception error, MessageVersion version, ref Message msg)
{
 if (error is DivideByZeroException)
        {
            MathFault mathFault = new MathFault();
            mathFault.Operation = error.Source;
            mathFault.ProblemType = error.Message + "Added by CalculatorErrorHandler";

            FaultException<MathFault> fault = new FaultException<MathFault>(mathFault);
            MessageFault messageFault = fault.CreateMessageFault();
            msg = Message.CreateMessage(version, messageFault, "http://FaultCalculator/MathFaultResponse");\;)
        }
}

MathFault is a DataContract type defined as follows:

 [DataContract]
    public class MathFault
    {
        private string operation;
        private string problemType;

        [DataMember]
        public string Operation
        {
            get { return operation; }
            set { operation = value; }
        }

        [DataMember]
        public string ProblemType
        {
            get { return problemType; }
            set { problemType = value; }
        }

    }

Please see the sample mentioned earlier for the code needed to hook up the IErrorHandler to your service.