Muokkaa

Jaa


How to: Declare Faults in Service Contracts

In managed code, exceptions are thrown when error conditions occur. In Windows Communication Foundation (WCF) applications, however, service contracts specify what error information is returned to clients by declaring SOAP faults in the service contract. For an overview of the relationship between exceptions and faults, see Specifying and Handling Faults in Contracts and Services.

Create a service contract that specifies a SOAP fault

  1. Create a service contract that contains at least one operation. For an example, see How to: Define a Service Contract.

  2. Select an operation that can specify an error condition about which clients can expect to be notified. To decide which error conditions justify returning SOAP faults to clients, see Specifying and Handling Faults in Contracts and Services.

  3. Apply a System.ServiceModel.FaultContractAttribute to the selected operation and pass a serializable fault type to the constructor. For details about creating and using serializable types, see Specifying Data Transfer in Service Contracts. The following example shows how to specify that the SampleMethod operation can result in a GreetingFault.

    [OperationContract]
    [FaultContractAttribute(
      typeof(GreetingFault),
      Action="http://www.contoso.com/GreetingFault",
      ProtectionLevel=ProtectionLevel.EncryptAndSign
      )]
    string SampleMethod(string msg);
    
    <OperationContract, FaultContractAttribute(GetType(GreetingFault), Action:="http://www.contoso.com/GreetingFault", ProtectionLevel:=ProtectionLevel.EncryptAndSign)> _
    Function SampleMethod(ByVal msg As String) As String
    
  4. Repeat steps 2 and 3 for all operations in the contract that communicate error conditions to clients.

Implementing an Operation to Return a Specified SOAP Fault

Once an operation has specified that a specific SOAP fault can be returned (such as in the preceding procedure) to communicate an error condition to a calling application, the next step is to implement that specification.

Throw the specified SOAP fault in the operation

  1. When a FaultContractAttribute-specified error condition occurs in an operation, throw a new System.ServiceModel.FaultException<TDetail> where the specified SOAP fault is the type parameter. The following example shows how to throw the GreetingFault in the SampleMethod shown in the preceding procedure and in the following Code section.

    throw new FaultException<GreetingFault>(new GreetingFault("A Greeting error occurred. You said: " + msg));
    
        Throw New FaultException(Of GreetingFault)(New GreetingFault("A Greeting error occurred. You said: " & msg))
    End If
    

Example

The following code example shows an implementation of a single operation that specifies a GreetingFault for the SampleMethod operation.

using System;
using System.Collections.Generic;
using System.Net.Security;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace Microsoft.WCF.Documentation
{
  [ServiceContract(Namespace="http://microsoft.wcf.documentation")]
  public interface ISampleService{
    [OperationContract]
    [FaultContractAttribute(
      typeof(GreetingFault),
      Action="http://www.contoso.com/GreetingFault",
      ProtectionLevel=ProtectionLevel.EncryptAndSign
      )]
    string SampleMethod(string msg);
  }

  [DataContractAttribute]
  public class GreetingFault
  {
    private string report;

    public GreetingFault(string message)
    {
      this.report = message;
    }

    [DataMemberAttribute]
    public string Message
    {
      get { return this.report; }
      set { this.report = value; }
    }
  }

  class SampleService : ISampleService
  {
  #region ISampleService Members

  public string  SampleMethod(string msg)
  {
    Console.WriteLine("Client said: " + msg);
    // Generate intermittent error behavior.
    Random rnd = new Random(DateTime.Now.Millisecond);
    int test = rnd.Next(5);
    if (test % 2 != 0)
      return "The service greets you: " + msg;
    else
      throw new FaultException<GreetingFault>(new GreetingFault("A Greeting error occurred. You said: " + msg));
  }

  #endregion
  }
}

Imports System.Collections.Generic
Imports System.Net.Security
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.Text

Namespace Microsoft.WCF.Documentation
    <ServiceContract(Namespace:="http://microsoft.wcf.documentation")> _
    Public Interface ISampleService
        <OperationContract, FaultContractAttribute(GetType(GreetingFault), Action:="http://www.contoso.com/GreetingFault", ProtectionLevel:=ProtectionLevel.EncryptAndSign)> _
        Function SampleMethod(ByVal msg As String) As String
    End Interface

    <DataContractAttribute> _
    Public Class GreetingFault
        Private report As String

        Public Sub New(ByVal message As String)
            Me.report = message
        End Sub

        <DataMemberAttribute> _
        Public Property Message() As String
            Get
                Return Me.report
            End Get
            Set(ByVal value As String)
                Me.report = value
            End Set
        End Property
    End Class

    Friend Class SampleService
        Implements ISampleService
#Region "ISampleService Members"

        Public Function SampleMethod(ByVal msg As String) As String Implements ISampleService.SampleMethod
            Console.WriteLine("Client said: " & msg)
            ' Generate intermittent error behavior.
            Dim rand As New Random(DateTime.Now.Millisecond)
            Dim test As Integer = rand.Next(5)
            If test Mod 2 <> 0 Then
                Return "The service greets you: " & msg
            Else
                Throw New FaultException(Of GreetingFault)(New GreetingFault("A Greeting error occurred. You said: " & msg))
            End If
        End Function

#End Region
    End Class
End Namespace

See also