wcf FaultException Reason

4.4k views Asked by At

For the following exception no Reason is specified in the exception window (->view details):

System.ServiceModel.FaultException The creator of this fault did not specify a Reason. How can I change it to show the reason? (I need 1234 to be shown there)

public class MysFaultException
{
    public string Reason1
    {
        get;
        set;
    }
}

MyFaultException connEx = new MyFaultException();
connEx.Reason1 = "1234";
throw new FaultException<OrdersFaultException>(connEx);
2

There are 2 answers

0
i3arnon On

The WCF service chose to not show the reason behind the general error using includeExceptionDetailInFaults="false". You can change it in the configuration file:

<services>
    <service name="serviceHost" behaviorConfiguration="serviceBehavior">
        <endpoint .... />
    </service>
</services>
<behaviors>
    <serviceBehaviors>
        <behavior name="serviceBehavior">
            <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
    </serviceBehaviors>
</behaviors>

You don't need to create your own exception. The FaultException will wrap the real exception thrown in your service and show you the message and relevant information.

3
Scott Chamberlain On

While I3arnon answer is good if you want all exceptions to be forwarded on to the callers, if you want only a limited set of known faults to come through you can create Fault Contracts which let the caller know a specific set of exceptions may be coming through so the client can be ready to handle them. This allows you to pass along potential expected exceptions without forwarding on all exceptions your software may throw on to the client.

Here is a simple example from the MSDN that shows a WCF service catching a DivideByZeroException and turning it in to a FaultException to be passed along on to the client.

[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
    //... (Snip) ...

    [OperationContract]
    [FaultContract(typeof(MathFault))]
    int Divide(int n1, int n2);
}

[DataContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public class MathFault
{    
    private string operation;
    private string problemType;

    [DataMember]
    public string Operation
    {
        get { return operation; }
        set { operation = value; }
    }

    [DataMember]        
    public string ProblemType
    {
        get { return problemType; }
        set { problemType = value; }
    }
}

//Server side function
public int Divide(int n1, int n2)
{
    try
    {
        return n1 / n2;
    }
    catch (DivideByZeroException)
    {
        MathFault mf = new MathFault();
        mf.operation = "division";
        mf.problemType = "divide by zero";
        throw new FaultException<MathFault>(mf);
    }
}