Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF custom fault exception not caught correctly in client

I'm trying to create some custom FaultException. I've made a DataContract class called 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; }
    }
}

I'm then throwing the fault in a service method.

In IService1.cs

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

and in Service1.cs

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

I catch the FaultException in my client.

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)
    {
    }
}

Now here comes the problem. When I create a WCF Service Application project in Visual Studio 2010 it works like expected. The error is caught in:

catch (FaultException<CreateFault> ex)

But when I create a WCF Service Library project with my custom FaultExceptions the client does not recognize my custom exception. It instead catches the error in:

catch (FaultException ex)

Why does it not work with WCF Service Application Project?

Edit: This is what i get during debugging when it catches the exception in

catch (FaultException ex)

(typed ?ex in Immediate window)

{"Message abt exception"}

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

Found the problem. I had two Service references who both had the CreateFault DataContract. And it was using the wrong one when i ran the program.

When i changed to

catch (FaultException<ServiceReference2.CreateFault> ex) 

it worked

like image 492
Johan Björk Avatar asked Feb 27 '12 10:02

Johan Björk


1 Answers

Found the problem. I had two Service references who both had the CreateFault DataContract. And it was using the wrong one when i ran the program.

When i changed to

catch (FaultException<ServiceReference2.CreateFault> ex) 

it worked

like image 152
Johan Björk Avatar answered Sep 19 '22 14:09

Johan Björk