作法:在服務合約中宣告錯誤

在 Managed 程式碼中,發生錯誤狀況時會擲回例外狀況。 但在 Windows Communication Foundation (WCF) 應用程式中,服務合約可以藉由在服務合約中宣告 SOAP 錯誤,指定傳回用戶端的錯誤資訊。 如需例外狀況與錯誤之間關聯性的概觀,請參閱在合約和服務中指定和處理錯誤

建立會指定 SOAP 錯誤的服務合約

  1. 建立其中至少包含一個作業的服務合約。 如需取得範例,請參閱操作說明:定義服務合約)。

  2. 選取作業,這個作業會指定用戶端預期會收到通知的錯誤狀況。 若要判定哪些錯誤條件要對用戶端傳回 SOAP 錯誤,請參閱指定及處理合約和服務中的錯誤

  3. System.ServiceModel.FaultContractAttribute 套用至選取的作業,並將可序列化的錯誤類型傳遞至建構函式。 如需建立和使用可序列化類型的詳細資料,請參閱在服務合約中指定資料傳輸。 下列範例將示範如何指定會在 SampleMethod 中產生 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. 對合約中會與用戶端溝通錯誤狀況的所有作業,重複步驟 2 和 3。

實作作業以傳回指定的 SOAP 錯誤

一旦作業已指定可傳回特定 SOAP 錯誤 (如之前的程序所示),以與呼叫應用程式溝通錯誤狀況,則下一個步驟就是實作該指定項目。

在作業中擲回指定的 SOAP 錯誤

  1. 在作業中發生 FaultContractAttribute 特定的錯誤狀況時,會擲回新的 System.ServiceModel.FaultException<TDetail>,其中指定的 SOAP 錯誤為型別參數。 下列範例會示範如何在之前程序中顯示的 GreetingFault 中擲回 SampleMethod,以及如何在下列「程式碼」區段中擲回。

    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
    

範例

下列程式碼範例會顯示對 GreetingFault 作業指定 SampleMethod 的單一作業實作。

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

另請參閱