IErrorHandler 接口

定义

允许实施者对返回给调用方的错误消息进行控制,还可以选择执行自定义错误处理,例如日志记录。Allows an implementer to control the fault message returned to the caller and optionally perform custom error processing such as logging.

public interface class IErrorHandler
public interface IErrorHandler
type IErrorHandler = interface
Public Interface IErrorHandler

示例

下面的代码示例演示了服务方法引发托管异常时,实现 IErrorHandler(仅返回类型为 FaultException<TDetail>GreetingFault)的服务。The following code example demonstrates a service that implements IErrorHandler that returns only FaultException<TDetail> of type GreetingFault when a service method throws a managed exception.

#region IErrorHandler Members
public bool HandleError(Exception error)
{
  Console.WriteLine("HandleError called.");
  // Returning true indicates you performed your behavior.
  return true;
}

// This is a trivial implementation that converts Exception to FaultException<GreetingFault>.
public void ProvideFault(
  Exception error,
  MessageVersion ver,
  ref Message msg
)
{
  Console.WriteLine("ProvideFault called. Converting Exception to GreetingFault....");
  FaultException<GreetingFault> fe
    = new FaultException<GreetingFault>(new GreetingFault(error.Message));
  MessageFault fault = fe.CreateMessageFault();
  msg = Message.CreateMessage(
    ver,
    fault,
    "http://microsoft.wcf.documentation/ISampleService/SampleMethodGreetingFaultFault"
  );
}
#endregion
#Region "IErrorHandler Members"
Public Function HandleError(ByVal [error] As Exception) As Boolean Implements IErrorHandler.HandleError
  Console.WriteLine("HandleError called.")
  ' Returning true indicates you performed your behavior.
  Return True
End Function

' This is a trivial implementation that converts Exception to FaultException<GreetingFault>.
Public Sub ProvideFault(ByVal [error] As Exception, ByVal ver As MessageVersion, ByRef msg As Message) Implements IErrorHandler.ProvideFault
  Console.WriteLine("ProvideFault called. Converting Exception to GreetingFault....")
  Dim fe As New FaultException(Of GreetingFault)(New GreetingFault([error].Message))
  Dim fault As MessageFault = fe.CreateMessageFault()
  msg = Message.CreateMessage(ver, fault, "http://microsoft.wcf.documentation/ISampleService/SampleMethodGreetingFaultFault")
End Sub
#End Region

下面的代码示例演示了如何使用服务行为将 IErrorHandler 实现添加到 ErrorHandlers 属性。The following code example shows how to use a service behavior to add the IErrorHandler implementation to the ErrorHandlers property.

// This behavior modifies no binding parameters.
#region IServiceBehavior Members
public void AddBindingParameters(
  ServiceDescription description,
  ServiceHostBase serviceHostBase,
  System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints,
  System.ServiceModel.Channels.BindingParameterCollection parameters
)
{
  return;
}

// This behavior is an IErrorHandler implementation and
// must be applied to each ChannelDispatcher.
public void ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
  Console.WriteLine("The EnforceGreetingFaultBehavior has been applied.");
  foreach(ChannelDispatcher chanDisp in serviceHostBase.ChannelDispatchers)
  {
    chanDisp.ErrorHandlers.Add(this);
  }
}

// This behavior requires that the contract have a SOAP fault with a detail type of GreetingFault.
public void Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
  Console.WriteLine("Validate is called.");
  foreach (ServiceEndpoint se in description.Endpoints)
  {
    // Must not examine any metadata endpoint.
    if (se.Contract.Name.Equals("IMetadataExchange")
      && se.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex"))
      continue;
    foreach (OperationDescription opDesc in se.Contract.Operations)
    {
      if (opDesc.Faults.Count == 0)
        throw new InvalidOperationException(String.Format(
          "EnforceGreetingFaultBehavior requires a "
          + "FaultContractAttribute(typeof(GreetingFault)) in each operation contract.  "
          + "The \"{0}\" operation contains no FaultContractAttribute.",
          opDesc.Name)
        );
      bool gfExists = false;
      foreach (FaultDescription fault in opDesc.Faults)
      {
        if (fault.DetailType.Equals(typeof(GreetingFault)))
        {
          gfExists = true;
          continue;
        }
      }
      if (gfExists == false)
      {
        throw new InvalidOperationException(
"EnforceGreetingFaultBehavior requires a FaultContractAttribute(typeof(GreetingFault)) in an operation contract."
        );
      }
    }
  }
}
#endregion
' This behavior modifies no binding parameters.
#Region "IServiceBehavior Members"
Public Sub AddBindingParameters(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase, ByVal endpoints As System.Collections.ObjectModel.Collection(Of ServiceEndpoint), ByVal parameters As System.ServiceModel.Channels.BindingParameterCollection) Implements IServiceBehavior.AddBindingParameters
  Return
End Sub

' This behavior is an IErrorHandler implementation and 
' must be applied to each ChannelDispatcher.
Public Sub ApplyDispatchBehavior(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase) Implements IServiceBehavior.ApplyDispatchBehavior
  Console.WriteLine("The EnforceGreetingFaultBehavior has been applied.")
  For Each chanDisp As ChannelDispatcher In serviceHostBase.ChannelDispatchers
    chanDisp.ErrorHandlers.Add(Me)
  Next chanDisp
End Sub

' This behavior requires that the contract have a SOAP fault with a detail type of GreetingFault.
Public Sub Validate(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase) Implements IServiceBehavior.Validate
  Console.WriteLine("Validate is called.")
  For Each se As ServiceEndpoint In description.Endpoints
    ' Must not examine any metadata endpoint.
    If se.Contract.Name.Equals("IMetadataExchange") AndAlso se.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex") Then
      Continue For
    End If
    For Each opDesc As OperationDescription In se.Contract.Operations
      If opDesc.Faults.Count = 0 Then
        Throw New InvalidOperationException(String.Format("EnforceGreetingFaultBehavior requires a " & "FaultContractAttribute(typeof(GreetingFault)) in each operation contract.  " & "The ""{0}"" operation contains no FaultContractAttribute.", opDesc.Name))
      End If
      Dim gfExists As Boolean = False
      For Each fault As FaultDescription In opDesc.Faults
        If fault.DetailType.Equals(GetType(GreetingFault)) Then
          gfExists = True
          Continue For
        End If
      Next fault
      If gfExists = False Then
        Throw New InvalidOperationException("EnforceGreetingFaultBehavior requires a FaultContractAttribute(typeof(GreetingFault)) in an operation contract.")
      End If
    Next opDesc
  Next se
End Sub
#End Region

下面的代码示例演示了如何通过使用应用程序配置文件来配置服务,从而加载服务行为。The following code example shows how to configure the service to load the service behavior using an application configuration file. 有关如何在配置文件中公开服务行为的详细信息,请参见 IServiceBehaviorFor more details about how to expose a service behavior in a configuration file, see IServiceBehavior.

<configuration>
  <system.serviceModel>
    <services>
      <service 
        name="Microsoft.WCF.Documentation.SampleService"
        behaviorConfiguration="metaAndErrors">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <endpoint
          address=""
          binding="wsHttpBinding"
          contract="Microsoft.WCF.Documentation.ISampleService"
         />
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"
         />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metaAndErrors">
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceMetadata httpGetEnabled="true"/>
          <enforceGreetingFaults />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add 
          name="enforceGreetingFaults" 
          type="Microsoft.WCF.Documentation.EnforceGreetingFaultBehavior, HostApplication, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
        />
      </behaviorExtensions>
    </extensions>
  </system.serviceModel>
</configuration>

注解

若要在引发异常时显式控制应用程序的行为,请实现 IErrorHandler 接口并将其添加到 ChannelDispatcher 的属性中 ErrorHandlersTo explicitly control the behavior of the application when an exception is thrown, implement the IErrorHandler interface and add it to the ChannelDispatcher's ErrorHandlers property. IErrorHandler使您能够显式控制生成的 SOAP 错误,决定是否将其发送回客户端,以及执行日志记录等相关任务。IErrorHandler enables you to explicitly control the SOAP fault generated, decide whether to send it back to the client, and perform associated tasks, such as logging. 错误处理程序将按照它们向 ErrorHandlers 属性中的添加顺序进行调用。Error handlers are called in the order in which they were added to the ErrorHandlers property.

实现 ProvideFault 方法可控制返回到客户端的错误消息。Implement the ProvideFault method to control the fault message that is returned to the client.

实现 HandleError 方法可确保执行错误相关行为,包括错误日志记录、确保快速报告故障、关闭应用程序等。Implement the HandleError method to ensure error-related behaviors, including error logging, assuring a fail fast, shutting down the application, and so on.

备注

由于 HandleError 方法可以从许多不同的位置进行调用,所以不能确保该方法调用的线程。Because the HandleError method can be called from many different places there are no guarantees made about which thread the method is called on. 不要依赖操作线程上调用的 HandleError 方法。Do not depend on HandleError method being called on the operation thread.

发送响应消息前,首先调用所有 ProvideFault 实现。All ProvideFault implementations are called first, prior to sending a response message. 如果 ProvideFault 为非 fault,则在调用了所有 null 实现且返回后,将根据操作协定将响应消息发送回客户端。When all ProvideFault implementations have been called and return, and if fault is non-null, it is sent back to the client according to the operation contract. 如果调用所有实现后,faultnull,则响应消息将由 ServiceBehaviorAttribute.IncludeExceptionDetailInFaults 属性值控制。If fault is null after all implementations have been called, the response message is controlled by the ServiceBehaviorAttribute.IncludeExceptionDetailInFaults property value.

备注

调用所有 ProvideFault 实现,并将响应消息传递到通道后,可能会发生异常。Exceptions can occur after all ProvideFault implementations are called and a response message is handed to the channel. 如果出现通道异常(例如,对消息进行序列化时出现困难), IErrorHandler 将通知对象。If a channel exception occurs (for example, difficulty serializing the message) IErrorHandler objects are notified. 在这种情况下,你仍应确保你的开发环境捕获并显示此类异常,或利用跟踪来发现问题。In this case, you should still make sure that your development environment catches and displays such exceptions to you or makes use of tracing to discover the problem. 有关跟踪的详细信息,请参阅使用跟踪对应用程序进行故障排除For more information about tracing, see Using Tracing to Troubleshoot Your Application.

发送响应消息后,将以相同顺序调用所有 HandleError 实现。After the response message has been sent, all HandleError implementations are called in the same order.

通常,会将 IErrorHandler 实现添加到服务的 ErrorHandlers 属性;如果为双工通信,则还要添加到客户端的上述属性中。Typically, an IErrorHandler implementation is added to the ErrorHandlers property on the service (and the client in the case of duplex communication).

您可通过实现行为(IErrorHandlerSystem.ServiceModel.Description.IServiceBehaviorSystem.ServiceModel.Description.IEndpointBehaviorSystem.ServiceModel.Description.IContractBehavior 对象)将 System.ServiceModel.Description.IOperationBehavior 添加到运行时,然后从配置文件、以编程方式使用所添加的行为,或利用自定义属性来附加您的 IErrorHandlerYou can add the IErrorHandler to the runtime by implementing a behavior (either an System.ServiceModel.Description.IServiceBehavior, System.ServiceModel.Description.IEndpointBehavior, System.ServiceModel.Description.IContractBehavior, or System.ServiceModel.Description.IOperationBehavior object) and use the behavior programmatically, from a configuration file or with a custom attribute to attach your IErrorHandler.

有关使用行为来修改运行时的详细信息,请参阅使用行为配置和扩展运行时For more information about using behaviors to modify the runtime, see Configuring and Extending the Runtime with Behaviors.

方法

HandleError(Exception)

启用错误相关处理并返回一个值,该值指示调度程序在某些情况下是否中止会话和实例上下文。Enables error-related processing and returns a value that indicates whether the dispatcher aborts the session and the instance context in certain cases.

ProvideFault(Exception, MessageVersion, Message)

启用创建从服务方法过程中的异常返回的自定义 FaultException<TDetail>Enables the creation of a custom FaultException<TDetail> that is returned from an exception in the course of a service method.

适用于