WCF異常處理

WCF服務開發者可能會遇到需要以適當的方式向客戶端報告一些不可預見的錯誤。這樣的錯誤,稱為異常,通常是通過使用try/catch塊來處理,但同樣,這是非常具體的技術。

由於客戶端的關注領域不是關於如何發生錯誤或因素導致的錯誤,SOAP錯誤的約定,用於從WCF服務的傳送到客戶端的錯誤消息。

故障分析合約使客戶端能夠發生在一個服務錯誤的檔視圖。下麵的例子給出了一個更好的瞭解。

步驟1:一個簡單的計算器服務與除法運算,將創建一般常見的異常。

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Runtime.Serialization;
usingSystem.ServiceModel;
usingSystem.Text;

namespace Calculator
{
   // NOTE: You can use the "Rename" command on the "Refactor" menu to change 
   // the interface name "IService1" in both code and config file together.

   [ServiceContract]

   public interface IService1
   {
      [OperationContract]
      int divide(int num1, int num2);
      // TODO: Add your service operations here by www.xuhuhu.com
   }
}

該類編碼檔顯示如下:

現在,當我們試圖讓10除以零,計算服務將拋出一個異常。


該異常可以通過try/catch塊來處理。

現在,當我們試圖讓任何整數除以0,它會因為我們在catch塊中處理其返回值10。

步驟-2:FaultException異常用於在該步驟中進行通信的異常資訊從服務客戶端返回。

public int Divide(int num1, int num2)
{
   //Do something 
   throw new FaultException("Error while dividing number");
}

上一篇: WCF安全 下一篇:無