wcf exceptions without showing a stacktrace

4.2k views Asked by At

I need to throw from wcf exceptions without showing a stacktrace to a client, just message...

throw new FaultException("ex1");

I have in average 20 exceptions strings. How do I implement it without throwing each time FaultException with string argument, but rather an exception object

FaultException_i i = 1...20
1

There are 1 answers

2
Cybermaxs On BEST ANSWER

When using WCF service, you have to use FaulException because it's the native Soap approach for handling errors. However, not all exceptions implement wcf serialization correctly.

Exception details (including stacktrace) should never be exposed to clients. Your can easily turn off this in config :

<system.serviceModel>
   <behaviors>
      <serviceBehaviors>
         <behavior name="MyServiceBehavior">
             <serviceDebug includeExceptionDetailInFaults="False" />
         </behavior>
      </serviceBehaviors>
   </behaviors>

   <services>
      <service name="MyService"
               behaviorConfiguration="MyServiceBehavior" >
          ....
      </service>
   </services>
</system.serviceModel>

In addition, I generaly use a custom data contract that will contain your exception information.

[DataContract]
public class MyFault
{
    [DataMember]
    public int Code { get; set; }
    [DataMember]
    public string Message { get; set; }
}

Then, I've just to throw a generic fault like this :

var myFault = new MyFault()
        {
            Code = ErrorCode.UnhandledException
            Message = ex.Message,
        };
...
throw new FaultException<MyFault>(myFault);