5

我正在尝试创建一些自定义FaultException。我开设了一个DataContract名为CreateFault.

[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)

但是,当我使用自定义创建 WCF 服务库项目时FaultExceptions,客户端无法识别我的自定义异常。相反,它会在以下位置捕获错误:

catch (FaultException ex)

为什么它不适用于 WCF 服务应用程序项目?

编辑:这是我在调试过程中捕获异常时得到的

catch (FaultException ex)

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

{"消息异常"}

[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}

编辑2:

发现了问题。我有两个服务引用,他们都有 CreateFault DataContract。当我运行程序时它使用了错误的。

当我改为

catch (FaultException<ServiceReference2.CreateFault> ex) 

有效

4

1 回答 1

5

发现了问题。我有两个服务引用,他们都有 CreateFault DataContract。当我运行程序时它使用了错误的。

当我改为

catch (FaultException<ServiceReference2.CreateFault> ex) 

有效

于 2012-02-28T07:27:23.203 回答