簡體   English   中英

客戶端無法正確捕獲WCF自定義故障異常

[英]WCF custom fault exception not caught correctly in client

我正在嘗試創建一些自定義的FaultException 我創建了一個名為CreateFaultDataContract類。

[DataContract]
public class CreateFault
{
    private string report;

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

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

然后我將故障拋在服務方法中。

IService1.cs

[OperationContract]
[FaultContract(typeof(CreateFault))]
void TestFaultException();

並在Service1.cs

public void TestFaultException()
{
    throw new FaultException<CreateFault>(new CreateFault("CreateFault message"), "Message abt exception");
}

我在客戶端捕獲FaultException

private void btnTest_Click(object sender, RoutedEventArgs e)
{
    try
    {
        ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
        client.TestFaultException();
    }
    catch (FaultException<CreateFault> ex)
    {
        MessageBox.Show(ex.Detail.Message, "Success", MessageBoxButton.OK, MessageBoxImage.Error);
    }
    catch (FaultException ex)
    {
        MessageBox.Show(ex.Message, "Failure", MessageBoxButton.OK, MessageBoxImage.Error);
    }
    catch (Exception ex)
    {
    }
}

現在問題來了。 當我在Visual Studio 2010中創建WCF服務應用程序項目時,它的工作方式與預期的一樣。 錯誤發生在:

catch (FaultException<CreateFault> ex)

但是,當我使用自定義FaultExceptions創建WCF服務庫項目時,客戶端無法識別我的自定義異常。 它反過來捕獲錯誤:

catch (FaultException ex)

為什么它不適用於WCF服務應用程序項目?

編輯:這是我在調試時獲取異常的結果

catch (FaultException ex)

(在立即窗口中鍵入?ex)

{“消息abt例外”}

[System.ServiceModel.FaultException<WpfApplication1.ServiceReference2.CreateFault>]: {"Message abt exception"}
base {System.ServiceModel.CommunicationException}: {"Message abt exception"}
Action: "http://tempuri.org/IService1/TestFaultExceptionCreateFaultFault"
Code: {System.ServiceModel.FaultCode}
Message: "Message abt exception"
Reason: {Message abt exception}

EDIT2:

發現了問題。 我有兩個Service引用,它們都有CreateFault DataContract。 當我運行該程序時,它使用了錯誤的一個。

當我改為

catch (FaultException<ServiceReference2.CreateFault> ex) 

有效

發現了問題。 我有兩個Service引用,它們都有CreateFault DataContract。 當我運行該程序時,它使用了錯誤的一個。

當我改為

catch (FaultException<ServiceReference2.CreateFault> ex) 

有效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM