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.yiibai.com } }

該類編碼文件顯示如下:
WCF異常處理

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

WCF異常處理

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

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

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

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

WCF異常處理