다음을 통해 공유


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

처리 중에 throw되는 예외입니다.

반환

Boolean

WCF(Windows Communication Foundation)가 세션(있는 경우)을 중단하지 않는 경우 true이고 인스턴스 컨텍스트가 Single이 아닌 경우 인스턴스 컨텍스트이며, 그렇지 않으면 false입니다. 기본값은 false입니다.

예제

다음 코드 예제에서는 서비스 메서드가 관리되는 예외를 IErrorHandler throw할 때만 형식 GreetingFault 을 반환 FaultException<TDetail> 하는 서비스를 구현하는 서비스를 보여 줍니다.

#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있는 경우) 예외가 있는 경우 디스패처는 세션을 중단하고 이 세션이 아닌 Single경우 InstanceContextMode 를 중단합니다InstanceContext. 그런 다음 예외가 처리되지 않은 것으로 간주되고 모든 상태가 손상된 것으로 간주됩니다.

HandleError 이 기본 동작을 방지하기 위해 반환 true 합니다. 오류 처리기가 반환 true 되면 실패한 요청과 연결된 상태를 계속 사용하는 것이 안전하다는 것을 WCF에 지시합니다.

메서드에서 반환 true 되는 오류 처리기가 없으면 예외가 처리되지 않은 것으로 간주되고 기본 응답이 적용되므로 세션 채널에서 System.ServiceModel.InstanceContext 통신할 ServiceBehaviorAttribute.InstanceContextMode 때 중단되고 채널이 설정되지 않을 수 InstanceContextMode.SingleHandleError 있습니다.

매개 변수는 error 절대로 throw되지 않으며 null throw된 예외 개체를 포함합니다.

적용 대상