- WCF 教程
- WCF - 首頁
- WCF - 概述
- WCF - 與 Web 服務的比較
- WCF - 開發人員工具
- WCF - 架構
- WCF - 建立 WCF 服務
- WCF - 託管 WCF 服務
- WCS - IIS 託管
- WCF - 自託管
- WCF - WAS 託管
- WCF - Windows 服務託管
- WCF - 使用 WCF 服務
- WCF - 服務繫結
- WCF - 例項管理
- WCF - 事務
- WCF - RIA 服務
- WCF - 安全性
- WCF - 異常處理
- WCF 資源
- WCF - 快速指南
- WCF - 有用資源
- WCF - 討論
WCF - 異常處理
WCF 服務開發人員可能會遇到一些無法預見的錯誤,需要以合適的方式向客戶端報告。這些錯誤,稱為異常,通常使用 try/catch 塊處理,但這又非常依賴於具體的技術。
由於客戶端關注的並非錯誤是如何發生的或導致錯誤的因素,因此 WCF 使用 SOAP 錯誤契約來將錯誤訊息從服務傳達給客戶端。
錯誤契約使客戶端能夠以文件化的方式檢視服務中發生的錯誤。以下示例可以更好地理解這一點。
步驟 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
}
}
類檔案的程式碼如下所示:
現在,當我們嘗試將數字 10 除以零時,計算器服務將丟擲一個異常。
可以使用 try/catch 塊處理異常。
現在,當我們嘗試將任何整數除以 0 時,它將返回 10,因為我們在 catch 塊中處理了它。
步驟 2 - 在此步驟中,使用 FaultException 將異常資訊從服務傳達給客戶端。
public int Divide(int num1, int num2) {
//Do something
throw new FaultException("Error while dividing number");
}
步驟 3 - 也可以建立自定義型別來使用 FaultContract 傳送錯誤訊息。建立自定義型別的必要步驟如下所述:
透過使用資料契約定義型別,並指定要返回的欄位。
服務操作由 FaultContract 屬性裝飾。還指定了型別名稱。
建立一個服務例項以引發異常,併為自定義異常屬性賦值。
廣告