首页 > 代码库 > IErrorHandler

IErrorHandler

/// <summary> /// WCF服务端异常处理器 /// </summary> public class WCF_ExceptionHandler : IErrorHandler{   #region IErrorHandler Members      /// <summary>    /// HandleError    /// </summary>    /// <param name="ex">ex</param>    /// <returns>true</returns>    public bool HandleError(Exception ex)   {      return true;   }      /// <summary>    /// ProvideFault    /// </summary>    /// <param name="ex">ex</param>    /// <param name="version">version</param>    /// <param name="msg">msg</param>    public void ProvideFault(Exception ex, MessageVersion version, ref Message msg)   {      //       //在这里处理服务端的消息,将消息写入服务端的日志       //       string err = string.Format("调用WCF接口 ‘{0}‘ 出错", ex.TargetSite.Name) ",详情:\r\n" ex.Message;      var newEx = new FaultException(err);            MessageFault msgFault = newEx.CreateMessageFault();      msg = Message.CreateMessage(version, msgFault, newEx.Action);   }      #endregion}

  

/// <summary> /// WCF服务类的特性 /// </summary> public class WCF_ExceptionBehaviourAttribute : Attribute, IServiceBehavior{   private readonly Type _errorHandlerType;      public WCF_ExceptionBehaviourAttribute(Type errorHandlerType)   {      _errorHandlerType = errorHandlerType;   }      #region IServiceBehavior Members      public void Validate(ServiceDescription description,   ServiceHostBase serviceHostBase)   {   }      public void AddBindingParameters(ServiceDescription description,   ServiceHostBase serviceHostBase,   Collection<ServiceEndpoint> endpoints,   BindingParameterCollection parameters)   {   }      public void ApplyDispatchBehavior(ServiceDescription description,   ServiceHostBase serviceHostBase)   {      var handler =      (IErrorHandler)Activator.CreateInstance(_errorHandlerType);            foreach (ChannelDispatcherBase dispatcherBase in      serviceHostBase.ChannelDispatchers)      {         var channelDispatcher = dispatcherBase as ChannelDispatcher;         if (channelDispatcher != null)         channelDispatcher.ErrorHandlers.Add(handler);      }   }      #endregion}

  [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
[WCF_ExceptionBehaviour(typeof(WCF_ExceptionHandler))]
public class AccountModuleService : IAccountModuleService
{
   
   //来源:C/S框架网(www.csframework.com) QQ:1980854898


}   

 

public class GlobalException : IErrorHandler    {        public bool HandleError(Exception error)        {            return true;        }        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)        {            //服务器端能够获取到错误方法            var ex = new FaultException(string.Format("Wcf错误接口方法{0}", error.TargetSite.Name));            MessageFault mf = ex.CreateMessageFault();            //fault = Message.CreateMessage(version, mf, ex.Action);        }    } public class GlobalExceptionHandlerBehaviourAttribute : Attribute, IServiceBehavior    {        private Type _Type;        public GlobalExceptionHandlerBehaviourAttribute(Type ExcepType)        {            this._Type = ExcepType;        }        public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)        {        }        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)        {            var Handle = (IErrorHandler)Activator.CreateInstance(_Type);            foreach (ChannelDispatcherBase dispatcherBase in                serviceHostBase.ChannelDispatchers)            {                var channelDispatcher = dispatcherBase as ChannelDispatcher;                if (channelDispatcher != null)                    channelDispatcher.ErrorHandlers.Add(Handle);            }        }        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)        {                    }    }[GlobalExceptionHandlerBehaviour(typeof(GlobalException))]    public class LoginService : ILoginContract    {        public string Login(string UserName, string UserPwd)        {            if (string.IsNullOrEmpty(UserPwd))            {                throw new Exception();            }            return UserName;        }    } public class Network    {        [DllImport("wininet")]        private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);        /// <summary>        /// 检测本机是否联网        /// </summary>        /// <returns></returns>        public static bool IsConnectedInternet()        {            int i = 0;            if (InternetGetConnectedState(out i, 0))            {                //已联网                return true;            }            else            {                //未联网                return false;            }        }        private static bool? IsInit = null;        static Thread th = null;        private static NetworkDelegate OnClose = null;        ~Network()        {                        if (OnClose != null) OnClose();        }        /// <summary>        /// 检测本机是否已经联网        /// </summary>        /// <param name="StartType"></param>        /// <param name="CheckTime"></param>        /// <param name="AllTime"></param>        /// <returns></returns>        public static void Start(NetworkStartTypeEnum StartType, TimeSpan CheckTime, int AllTime)        {            th = new Thread(() =>            {                while (true)                {                    bool Content = IsConnectedInternet();                    if(IsInit==null)IsInit = Content;                    if (Content == false && IsInit == true)                    {                        OnUnConnection();                    }                    else if (Content == true && IsInit == false)                    {                        OnConnection();                    }                    IsInit = Content;                    Thread.Sleep(CheckTime);                }            });            th.IsBackground = true;            OnClose += () =>            {                try                {                    th.Abort();                }                catch { }            };            th.Start();            if (StartType == NetworkStartTypeEnum.JustTime)            {                Thread closeThread = new Thread(() =>                {                    Thread.Sleep(AllTime);                });                closeThread.IsBackground = true;                OnClose += () =>                {                    try                    {                        closeThread.Abort();                    }                    catch { }                };                closeThread.Start();            }        }        //本地委托        public delegate void NetworkDelegate();        /// <summary>        /// 当连上网的时候        /// </summary>        public static event NetworkDelegate OnConnection;        /// <summary>        /// 当没连上的时候        /// </summary>        public static event NetworkDelegate OnUnConnection;    }    public enum NetworkStartTypeEnum{        ApplicationExit,        JustTime    }

  

   public class ServiceErrorHandler : IErrorHandler    {        public bool HandleError(Exception error)        {            return true;        }        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)        {            FaultException<string> fex = new FaultException<string>(error.Message);            MessageFault mf = fex.CreateMessageFault();            fault = Message.CreateMessage(version, mf, "http://zh-ja-demo/svfault");        }    }[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]    public class MyContractBehaviorAttribute : Attribute, IContractBehavior    {        public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)        {                    }        public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)        {        }        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)        {            ServiceErrorHandler sverr = new ServiceErrorHandler();            dispatchRuntime.ChannelDispatcher.ErrorHandlers.Add(sverr);        }        public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)        {        }    }//--------------------------------------------------------    [FaultContract(typeof(string), Action = "http://zh-ja-demo/svfault")]        long RunWork(int bs);

  

 

IErrorHandler