次の方法で共有


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

サービス操作の過程でスローされる Exception オブジェクト。

version
MessageVersion

メッセージの SOAP バージョン。

fault
Message

クライアントまたはサービス (双方向の場合) に返される Message オブジェクト。

次のコード例では、サービス メソッドがマネージド例外をスローしたときに、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>

注釈

ProvideFault メソッドを実装して、クライアントに返されるカスタムのエラー メッセージを作成します。 WCF ProvideFault ランタイムが例外を特に致命的と認識し、例外自体を再スローする場合を除き、操作を終了する例外に対しては常にメソッドが呼び出されます。 すべての ProvideFault 実装が呼び出されたときに、エラー メッセージがクライアントに返されます (faultnull 以外の場合)。 パラメーターが fault 既定のエラーである null 場合は、クライアントに送信されます。

注意

処理エラーの原因となった受信メッセージは、このメソッドの間に OperationContext.RequestContext プロパティから入手できます。

注意

ProvideFault メソッドはさまざまな場所から呼び出すことができるため、このメソッドがどのスレッドで呼び出されるのかについての保証はありません。 ProvideFault メソッドが操作スレッドで呼び出されるとは限りません。

適用対象