There are 2 ways of handling errors in WCF.
1. Set the behavior property to enable client side to get the server error
you can add this XML delaration to your behavior.
- <serviceDebug includeExceptionDetailInFaults="true"/>
Then you can throw your exception like this
- throw new Exception("My Simple exception!");
At client side, you can capture the error using
- try
- {
- calling server operation....
- }
- catch (FaultException fe)
- {
- MessageBox.Show(fe.Message);
- }
The wead point for this method to handle the error is that, any error will be throw to client side, it may include some key information of the server which is not safe. The better way of doing this is to encapsual the error to a SOAP error.
Now i will introduce the second way of handling error
1. Define your own error class.
- [DataContract]
- public class FaultClass
- {
- private string info;
- public FaultClass(string message)
- {
- this.info = message;
- }
- [DataMember]
- public string msg
- {
- get { return info; }
- set { info = value; }
- }
- }
2. In your service operations, you have to register your error like this,
- [ServiceContract(SessionMode = SessionMode.Required)]
- public interface IServiceClass
- {
- [OperationContract]
- [FaultContract(typeof(FaultClass))]
- string GetText();
- }
3.After this, you can throw the exception in your service operation
- throw new FaultException<FaultClass>(new FaultClass("My SOAP fault"));
4. Then at client side, you can catch the error:(Please add service reference firstly.)
- try
- {
- Calling service operation...
- }
- catch (FaultException<TCP.FaultClass> ex)
- {
- MessageBox.Show(ex.Detail.msg);
- }