Fault Exceptions in WCF


Exceptions thrown by WCF service are treated as Fault exceptions. As a developer we should gracefully handle these kind of exceptions. Let's take a look at this by an example/

Service Contract -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[ServiceContract]
    public interface IService2
    {
        [OperationContract]
        [FaultContract(typeof(MyException))]
        [DebuggerStepThrough]
        MyException GetData(int value);
    }

    [DataContract]
    public class MyException 
    {
        [DataMember]
        public bool Result { get; set; }

        [DataMember]
        public string ErrorMessage { get; set; }

        [DataMember]
        public Exception MyInnerException { get; set; }

        [DataMember]
        public string ClientMessage { get; set; }
    }


Service Implementation -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Service1 : IService2
    {
       
        public MyException GetData(int value)
        {
            MyException mx = new MyException();
            try
            {
                double a = 44;
                if (value == 0)
                {
                    throw new DivideByZeroException();
                }
                double res = a / value;
                mx.ClientMessage = "Everything is well";
                mx.Result = true;
                return mx;
            }
            catch (DivideByZeroException dvex)
            {
                mx.Result = true;
                mx.ClientMessage = "Divide by zero";
                mx.MyInnerException = dvex;
                mx.ErrorMessage = dvex.StackTrace;
                throw new FaultException<MyException>(mx, dvex.ToString());
            }                    

        }
    }


Client (aspx.cs page) -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
try
            {
                FaultContractsDemo.ServiceReference1.Service2Client o = new ServiceReference1.Service2Client();
                MyException data = o.GetData(0);
                if (data.Result)
                    lblMessage.Text = "All is well";
            }
            catch (FaultException<MyException> ex)
            {
                lblMessage.Text = ex.Detail.ClientMessage;
            }


The service layer throws an exception, but client never recieves any. I am getting unhandled exception like,
The underlying connection was closed: The connection was closed unexpectedly.
 WCF does not like serializing the DivideByZeroException or any root exception caused at service layer, which is necessary to get it across the wire. Commenting out this would work as expected.

No comments:

Post a Comment