다음을 통해 공유


IErrorHandler.ProvideFault(Exception, MessageVersion, Message) 메서드

정의

서비스 메서드 중에 발생한 예외로부터 반환되는 사용자 지정 FaultException<TDetail>을 만들 수 있습니다.

public:
 void ProvideFault(Exception ^ error, System::ServiceModel::Channels::MessageVersion ^ version, System::ServiceModel::Channels::Message ^ % fault);
public:
 void ProvideFault(Exception ^ exception, System::ServiceModel::Channels::MessageVersion ^ version, System::ServiceModel::Channels::Message ^ % fault);
public void ProvideFault (Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault);
public void ProvideFault (Exception exception, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault);
abstract member ProvideFault : Exception * System.ServiceModel.Channels.MessageVersion * Message -> unit
abstract member ProvideFault : Exception * System.ServiceModel.Channels.MessageVersion * Message -> unit
Public Sub ProvideFault (error As Exception, version As MessageVersion, ByRef fault As Message)
Public Sub ProvideFault (exception As Exception, version As MessageVersion, ByRef fault As Message)

매개 변수

errorexception
Exception

서비스 작업 중에 throw되는 Exception 개체입니다.

version
MessageVersion

메시지의 SOAP 버전입니다.

fault
Message

클라이언트 또는 서비스(양방향인 경우)에 반환되는 Message 개체입니다.

예제

다음 코드 예제에서는 서비스 메서드가 관리되는 예외를 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>

설명

클라이언트에 ProvideFault 반환되는 사용자 지정 오류 메시지를 만드는 메서드를 구현합니다. WCF 런타임이 ProvideFault 예외를 특히 치명적으로 인식하고 예외 자체를 다시 throw하는 경우를 제외하고 작업을 종료하는 예외에 대해 메서드가 항상 호출됩니다. 모든 ProvideFault 구현이 호출되면 오류 메시지가 클라이언트로 다시 전송됩니다(비인null 경우fault). 매개 변수가 fault 기본 오류인 null 경우 클라이언트로 전송됩니다.

참고

처리 오류를 발생시킨 인바운드 메시지는 속성에서 OperationContext.RequestContext 이 메서드 중에 사용할 수 있습니다.

참고

메서드를 ProvideFault 여러 위치에서 호출할 수 있으므로 메서드가 호출되는 스레드에 대한 보장은 없습니다. 작업 스레드에서 ProvideFault 호출되는 메서드에 의존하지 마세요.

적용 대상