Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to throw exception over WCF

Tags:

c#

.net

wcf

I'm trying to send exceptions over WCF in the most generic way possible. Here's what I've got:

[ServiceContract]
interface IContract
{
    [OperationContract]
    void Foo();
}

class ContractImplementation: IContract
{
    public void Foo()
    {
        try
        {
            Bar();
        }
        catch (Exception ex)
        {
            throw new FaultException<Exception>(ex, ex.Message);
        }
    }
}

The exception that is actually coming out of Bar is:

[Serializable]
class MyException : Exception
{
    // serialization constructors
}

The error I'm seeing in the server-side WCF logging is:

Type 'MyException' with data contract name 'MyException:http://schemas.datacontract.org/2004/07/MyException' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

What I've tried so far:

[ServiceKnownType(typeof(MyException))]
[ServiceContract]
interface IContract
{
    [FaultContract(typeof(MyException))]
    [OperationContract]
    void Foo();
}

But no luck.

like image 592
Tudor Avatar asked Jun 30 '15 12:06

Tudor


People also ask

Which type of behavior should be configured to return exception detail from WCF service?

We can use FaultException &/or FaultContract (in System. ServiceModel namespace) to these exception details to the client.

How fault contract is implemented in WCF?

WCF provides the option to handle and convey the error message to the client from a service using a SOAP Fault Contract. To support SOAP Faults, WCF provides the FaultException class. This class has two forms: FaultException: to send an untyped fault back to the caller.


1 Answers

First, in MyException, remove the inheritance from Exception and make it public.

Second, when you declare your service contract, declare exception as it follows:

[FaultContractAttribute(
        typeof(MyException),
        Action = "", 
        Name = "MyException", 
        Namespace = "YourNamespace")]
    [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults = true)]
    [OperationContract]
    void Foo()

Finally, you can throw your Exception like this:

throw new FaultException<MyException>
             (
                 new MyException(ex.Message),
                 new FaultReason("Description of your Fault")

             );

Hope it helps.

like image 85
Ricardo Pontual Avatar answered Oct 26 '22 23:10

Ricardo Pontual