How to Implement a Data Contract To Propagate Exception Details for Debugging Purposes

- J.D. Meier, Carlos Farre, Jason Taylor, Prashant Bansode, Steve Gregersen, Madhu Sundararajan, Rob Boucher

The following steps shows how to implement a data contract to propagate exception details for debugging purposes
  1. Create a DataContract, with a member for fault reason
    [DataContract]
    public class MyDCFaultException
    {
        private string _reason;

        [DataMember]
        public string Reason
        {
            get { return _reason; }
            set { _reason = value; }
        }
    }
  1. Create a Service contract, specifiying a FaultContract with the above DataContract type for an operation
    [ServiceContract()]
    public interface IService
    {
        [OperationContract]
        [FaultContract(typeof(MyDCFaultException))]
        string DoSomeComplexWork();
    }
  1. Implement the service operation. If there are any error in the service operation send the exception details by throwing the FaultException of type MyDCFaultException as below
    public class Service : IService
    {    
        public string DoSomeComplexWork()
        {
           try
            {
                // some complex operations
            }
            catch (Exception exp)
            {
                MyDCFaultException theFault = new MyDCFaultException();
                theFault.Reason = "Some Error " + exp.Message.ToString();
                throw new FaultException<MyDCFaultException>(theFault);
            }
            return "No Error";
        }
    }
  1. Call the service operation from a client application. Get the original service exception reason by using the Detail.Reason property.
           try
            {
                localhost.IService proxy = new localhost.ServiceClient();
                result = proxy.DoSomeComplexWork();
            }

            catch (FaultException<localhost.MyDCFaultException> ex)
            {
               result = "Exception: " + ex.Detail.Reason;
            }

            Console.WriteLine(result);
            Console.ReadLine();            

You can also send managed exception information to the clients using the IncludeExceptionDetailInFaults property in the serviceDebug element of your service behavior. By default its value is false, you can change it to true for debugging or problem diagnosis scenarios.
<system.serviceModel>
    <services>
        <service name="MyService"
                         behaviorConfiguration="MyServiceBehavior">
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="MyServiceBehavior">
*                <serviceDebug includeExceptionDetailInFaults="true"/>*
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>

Additional Resources

Last edited Jun 13, 2008 at 6:45 PM by prashantbansode, version 1

Comments

No comments yet.