客户端WCF ExceptionHandler

时间:2014-10-08 09:26:31

标签: c# wcf client-side

是否可以使用BehaviorExtension处理客户端上的TimeoutException,EndpointNotFoundException,OperationTimeoutException等错误?

每次我使用WCF代理时,我都不想尝试使用catch-log-restart-connection。

此代码不起作用:

Behavyior:

public class EndpointBehavior:IEndpointBehavior
{
    public void Validate(ServiceEndpoint endpoint)
    {

    }

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {

    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {


    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        var handler = new WcfErrorHandler();
        clientRuntime.CallbackDispatchRuntime.ChannelDispatcher.ErrorHandlers.Add(handler);
    }
}

处理程序:

public class WcfErrorHandler:IErrorHandler
{
    public bool HandleError(Exception error)
    {
        Log.Instance.Trace(@"WCF Service Error:", error);
        return true;
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        var newEx = new FaultException(
           string.Format(@"Exception caught at WcfErrorHandler{0} Method: {1}{2}Message:{3}",
                        Environment.NewLine, error.TargetSite.Name, Environment.NewLine, error.Message));

        var msgFault = newEx.CreateMessageFault();
        fault = Message.CreateMessage(version, msgFault, newEx.Action);
    }

}

app.config的扩展名

public class ExceptionLogBehaviorExtensionElement : BehaviorExtensionElement
{
    public override Type BehaviorType
    {
        get 
        {
            return typeof(EndpointBehavior);
        }
    }

    protected override object CreateBehavior()
    {
        return new EndpointBehavior();
    }
}

0 个答案:

没有答案