Error handling in WCF

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.

  1. <serviceDebug includeExceptionDetailInFaults="true"/>

Then you can throw your exception like this

  1. throw new Exception("My Simple exception!");

At client side, you can capture the error using

  1. try
  2.             {
  3.                 calling server operation....
  4.             }
  5.             catch (FaultException fe)
  6.             {
  7.                 MessageBox.Show(fe.Message);
  8.             }

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.

 

  1. [DataContract]
  2.     public class FaultClass
  3.     {
  4.         private string info;
  5.         public FaultClass(string message)
  6.         {
  7.             this.info = message;
  8.         }
  9.         [DataMember]
  10.         public string msg
  11.         {
  12.             get { return info; }
  13.             set { info = value; }
  14.         }
  15.     }

2. In your service operations, you have to register your error like this,

  1.  [ServiceContract(SessionMode = SessionMode.Required)]
  2.     public interface IServiceClass
  3.     {
  4.         [OperationContract]
  5.         [FaultContract(typeof(FaultClass))]
  6.         string GetText();
  7.     }

3.After this, you can throw the exception in your service operation

  1. throw new FaultException<FaultClass>(new FaultClass("My SOAP fault"));

4. Then at client side, you can catch the error:(Please add service reference firstly.)

  1. try
  2.             {
  3.                 Calling service operation...
  4.             }
  5.             catch (FaultException<TCP.FaultClass> ex)
  6.             {
  7.                 MessageBox.Show(ex.Detail.msg);
  8.             }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值