Fault Contract in
WCF
With the help of fault contract we can describe how to
exchange error information from service to client. If we get any error in the
service then we can pass this error information from service to client with the
help of Fault contract.
For Example:-
Everybody is familiar with the error DivideByZero. It occurs
when we try to divide a number with zero, It occurs this exception. Same example
I am using here.
I create Error class which will be used to pass to the
client at the time of error occur:-
[DataContract]
public class Error
{
[DataMember]
public string
ErrorMessage;
[DataMember]
public string
ErrorMethod;
}
Now declare the method in contract class. While creating
the method you have to assign the fault contract to the method and describe the
type of error which we pass to the client. Here it is the type of Error Class.
[ServiceContract]
public interface ITechAltum
{
[OperationContract]
[FaultContract(typeof(Error))]
int div(int x, int y);
}
Now implement
this method in the Class where we use exception handling.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
public class TechAltum:ITechAltum
{
public int div(int x, int y)
{
try
{
int z = x / y;
return z;
}
catch(Exception e)
{
Error er=new Error();
er.ErrorMessage="You attempted to
divide by zero";
er.ErrorMethod="Div";
throw new FaultException<Error>(er);
}
}
}
Now implement it
at the client side:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ServiceModel;
public partial class _Default :
System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
try
{
ServiceReference1.TechAltumClient
svctech = new ServiceReference1.TechAltumClient();
int z = svctech.div(5, 0);
}
catch (FaultException<ServiceReference1.Error> er)
{
Response.Write(er.Detail.ErrorMessage);
Response.Write(er.Detail.ErrorMethod);
}
}
}
Hope you enjoyed the article.
Note:-kindly add namespace System.ServiceModel
where you use falut contract.
No comments:
Post a Comment