【问题标题】:should I wrap all my WCF service code in a try catch block?我应该将所有 WCF 服务代码包装在 try catch 块中吗?
【发布时间】:2012-04-24 07:05:41
【问题描述】:
try
{
    ///// here is the code that might throw erros. If I discover the user is unauthorized I throw a WebFaultException myself to alert the client
}      
catch (WebFaultException ex)
{
    throw ex; //but if I wrap all code in try-catch, I have to rethrow the exception o the status code reaches the client
}
catch (Exception ex)
{
    throw new WebFaultException(ex.Message, HttpStatusCode.InternalServerError);
}

我应该将所有内容都包装在 try-catch 中,还是您有什么建议?我将 WCF 与完整的 JSON 服务一起使用

【问题讨论】:

    标签: c# .net wcf try-catch


    【解决方案1】:

    你可以这样做,但最好在你的服务中实现 IErrorHandleradd it as a behaviour,这将允许在一个地方处理你未处理的异常,这样你就可以创建一个错误向用户返回详细信息。

    ErrorHandler : IErrorHandler
    {
    ... just implement the handling of errors here, however you want to handle them
    }
    

    然后创建一个使用它的行为:

    /// <summary>
    ///   Custom WCF Behaviour for Service Level Exception handling.
    /// </summary>
    public class ErrorHandlerBehavior : IServiceBehavior
        {
        #region Implementation of IServiceBehavior
    
    
        public void Validate (ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
            {
            }
    
    
        public void AddBindingParameters (ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
                                          Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
            {
            }
    
    
        public void ApplyDispatchBehavior (ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
            {
            IErrorHandler errorHandler = new ErrorHandler ();
    
            foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
                {
                var channelDispatcher = channelDispatcherBase as ChannelDispatcher;
    
                if (channelDispatcher != null)
                    {
                    channelDispatcher.ErrorHandlers.Add (errorHandler);
                    }
                }
            }
    
        #endregion
        }
    

    然后,如果您是自托管,则可以通过编程方式添加行为:

     myServiceHost.Description.Behaviors.Add (new ErrorHandlerBehavior ());
    

    如果您想通过配置添加它,那么您需要以下之一:

    public class ErrorHandlerElement : BehaviorExtensionElement
        {
        public override Type BehaviorType
            {
            get { return typeof (ErrorHandlerBehavior); }
            }
    
        protected override object CreateBehavior ()
            {
            return new ErrorHandlerBehavior ();
            }
        }
    }
    

    然后是配置:

    <system.serviceModel>
    <extensions>
      <behaviorExtensions>
        <add name="ErrorLogging" type="ErrorHandlerBehavior, ErrorHandling, Version=1.0.0.0, Culture=neutral, PublicKeyToken=<whatever>" />
      </behaviorExtensions>
    </extensions>
    <bindings>
      <basicHttpBinding>
        <binding name="basicBinding">
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="Service1Behavior" name="Service">
        <endpoint address="" binding="basicHttpBinding"  bindingConfiguration="basicBinding" contract="Service" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Service1Behavior">
          <serviceMetadata httpGetUrl="" httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <ErrorLogging />  <--this adds the behaviour to the service behaviours -->
        </behavior>
      </serviceBehaviors>
    </behaviors>
    

    【讨论】:

    • @EtherDragon 链接示例展示了如何以编程方式添加行为。
    猜你喜欢
    • 2012-02-18
    • 1970-01-01
    • 2010-09-26
    • 2018-09-14
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    相关资源
    最近更新 更多