[英]should I wrap all my WCF service code in a try catch block?
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服務一起使用
您可以這樣做,但是最好實現IErrorHandler 並將其作為行為添加到服務中,這樣可以將未處理的異常在一個地方處理,因此您可以在其中創建錯誤異常向用戶返回詳細信息。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.