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.tw511.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"); 
}