2012-04-23 7 views
6
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); 
} 

¿Debo envolver todo en un try-catch, o qué recomiendas? Utilizo WCF con servicios JSON relajantes¿debo envolver todo mi código de servicio WCF en un bloque try catch?

Respuesta

15

que podría ser mejor, pero probablemente sería mejor implementar IErrorHandler y add it as a behaviour en su servicio, lo que permitirá que las excepciones no manejadas se manejen en un solo lugar, por lo que ser capaz de crear una excepción de falla allí para devolver detalles a los usuarios.

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

a continuación para crear un comportamiento que utiliza esta:

/// <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 
    } 

Entonces, si usted tiene su propio anfitrión puede simplemente añadir el comportamiento mediante programación:

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

si desea agregarlo a través de la configuración, entonces necesita uno de estos:

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

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

y luego la configuración:

<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> 

+0

Hey Sam, cualquier posibilidad de un ejemplo de código en su respuesta? – EtherDragon

+0

@EtherDragon el ejemplo vinculado muestra cómo agregar el comportamiento mediante programación. –

+0

@AbuHamzah, ejemplos actualizados y agregados –

Cuestiones relacionadas