IErrorHandler.HandleError(Exception) 方法

定义

启用错误相关处理并返回一个值,该值指示调度程序在某些情况下是否中止会话和实例上下文。

public:
 bool HandleError(Exception ^ error);
public:
 bool HandleError(Exception ^ exception);
public bool HandleError (Exception error);
public bool HandleError (Exception exception);
abstract member HandleError : Exception -> bool
abstract member HandleError : Exception -> bool
Public Function HandleError (error As Exception) As Boolean
Public Function HandleError (exception As Exception) As Boolean

参数

errorexception
Exception

处理过程中引发的异常。

返回

Boolean

如果 Windows Communication Foundation (WCF) 不应中止会话(如果有一个)和实例上下文(如果实例上下文不是 Single),则为 true;否则为 false。 默认值为 false

示例

下面的代码示例演示了服务方法引发托管异常时,实现 IErrorHandler(仅返回类型为 FaultException<TDetail>GreetingFault)的服务。

#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 属性。

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

下面的代码示例演示了如何通过使用应用程序配置文件来配置服务,从而加载服务行为。 有关如何在配置文件中公开服务行为的详细信息,请参见 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>

注解

使用 HandleError 方法可实现错误相关行为(例如错误日志记录、系统通知、关闭应用程序等)并返回一个值,该值指定异常是否已适当处理。

备注

由于 HandleError 方法可以从许多不同的位置进行调用,所以不能确保该方法调用的线程。 不要依赖操作线程上调用的 HandleError 方法。

将调用所有 IErrorHandler 实现。 (默认情况下,当返回值 false) 时,如果存在异常,调度程序会中止任何会话,并中止 InstanceContextInstanceContextMode 其他任何会话以外的任何 Single会话。 这样,该异常被视为未处理,并且任何状态都被视为已损坏。

true 返回 HandleError 可以防止此默认行为。 如果任何错误处理程序返回 true ,则指示 WCF 使用与失败请求关联的状态是安全的。

当通过会话通道进行通信,或 true 属性未设置为 HandleError 时,如果没有错误处理程序从 System.ServiceModel.InstanceContext 方法返回 ServiceBehaviorAttribute.InstanceContextMode,则将认为异常未处理且默认响应适用,并可能会导致中止 InstanceContextMode.Single 和通道。

error 参数包含有所引发的异常对象,且永远不会为 null

适用于