错误契约[FaultContract]

服务端:

    [ServiceContract]
    interface ITTest 

    {
         [OperationContract]
        [FaultContract(typeof(DivideByZeroException))]
        [FaultContract(typeof(ExceptionDetail))]
        [FaultContract(typeof(ErrorInfo))]
        double Divide(double Number1, double number2);
    }

 

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, IncludeExceptionDetailInFaults = true)]
    class TTest : ITTest
    {
         public double Divide(double number1, double number2)
        {
            if (number2 == 0)
            {
                //DivideByZeroException dz = new DivideByZeroException("not is 0");
                //throw new FaultException<DivideByZeroException>(dz, dz.Message);

                ErrorInfo calException = new ErrorInfo();
                calException.ErrorCode = "8888888";
                calException.ErrorMessage = "Divide zero exception";
                FaultException<ErrorInfo> fault = new FaultException<ErrorInfo>(calException, "error");
                throw fault;
            }

            try
            {
                File.Open(@"m:\aaa.txt", FileMode.Open);
            }
            catch
            {
                ExceptionDetail ed = new ExceptionDetail(new Exception("无此文件"));
                throw new FaultException<ExceptionDetail>(ed, "not found file");
                //throw new FaultException<ErrorInfo>();
            }
            return number1 / number2;
        }
    }

 

自定义错误契约:

    public class ErrorInfo
    {
        private string errorCode = string.Empty;
        [DataMember]
        public string ErrorCode
        {
            get { return errorCode; }
            set { errorCode = value; }
        }

        private string errorMessage = string.Empty;
        [DataMember]
        public string ErrorMessage
        {
            get { return errorMessage; }
            set { errorMessage = value; }
        }
    }

 

客户端:

 ITTest HttpProxy = ChannelFactory<ITTest>.CreateChannel(new BasicHttpBinding(), new EndpointAddress("http://localhost:8001"));

            using (HttpProxy as IDisposable)
            {
                 try
                {
                    Console.WriteLine(HttpProxy.Divide(8, 0));
                }

                catch (FaultException<DivideByZeroException> exception)
                {

                }

                catch (FaultException<ExceptionDetail> eee)
                {

                }

                catch (FaultException<ErrorInfo> eee2)
                {
                    Console.WriteLine(HttpProxy.Divide(8, 2));
                }

                catch (CommunicationException ex)
                {
                    //FaultException fe = (FaultException)ex;
                }
            }

 

如果不定义  [FaultContract(typeof(ErrorInfo))]那么错误异常 将在客户端CommunicationException中截获 

 

你可能感兴趣的:(错误契约[FaultContract])