C# 我是否应该将所有WCF服务代码包装在一个try-catch块中?
我应该用试一试的方式来包装,还是你推荐什么?我将WCF与rest-ful JSON服务一起使用,您可以这样做,但最好是实现并使用您的服务,这将允许在一个地方处理未处理的异常,因此您可以在那里创建一个错误异常,以将详细信息返回给用户C# 我是否应该将所有WCF服务代码包装在一个try-catch块中?,c#,.net,wcf,try-catch,C#,.net,Wcf,Try Catch,我应该用试一试的方式来包装,还是你推荐什么?我将WCF与rest-ful JSON服务一起使用,您可以这样做,但最好是实现并使用您的服务,这将允许在一个地方处理未处理的异常,因此您可以在那里创建一个错误异常,以将详细信息返回给用户 try { ///// here is the code that might throw erros. If I discover the user is unauthorized I throw a WebFaultException myself to
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);
}
然后,要创建一个使用此选项的行为:
ErrorHandler : IErrorHandler
{
... just implement the handling of errors here, however you want to handle them
}
如果要通过配置添加,则需要以下选项之一:
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 ();
}
}
}
@EtherDragon链接的示例显示了如何以编程方式添加行为。
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>