為你解決WCF異常問題
WCF還是比較常用的,于是我研究了一下WCF,在這里拿出來和大家分享一下,希望對大家有用。異常消息與特定技術有關,.NET異常同樣如此,因而WCF并不支持傳統(tǒng)的異常處理方式。如果在WCF服務中采用傳統(tǒng)的方式處理異常,由于異常消息不能被序列化,因而客戶端無法收到服務拋出的WCF異常,例如這樣的服務設計:
- [ServiceContract(SessionModeSessionMode = SessionMode.Allowed)]
- public interface IDocumentsExplorerService
- {
- [OperationContract]
- DocumentList FetchDocuments(string homeDir);
- }
- [ServiceBehavior(InstanceContextModeInstanceContextMode=InstanceContextMode.Single)]
- public class DocumentsExplorerService : IDocumentsExplorerService,IDisposable
- {
- public DocumentList FetchDocuments(string homeDir)
- {
- //Some Codes
- if (Directory.Exists(homeDir))
- {
- //Fetch documents according to homedir
- }
- else
- {
- throw new DirectoryNotFoundException(
- string.Format("Directory {0} is not found.",homeDir));
- }
- }
- public void Dispose()
- {
- Console.WriteLine("The service had been disposed.");
- }
- }
則客戶端在調用如上的服務操作時,如果采用如下的捕獲方式是無法獲取該WCF異常的:
- catch (DirectoryNotFoundException ex)
- {
- //handle the exception;
- }
為了彌補這一缺陷,WCF會將無法識別的異常均當作為FaultException異常對象,因此,客戶端可以捕獲FaultException或者Exception異常:
- catch (FaultException ex)
- {
- //handle the exception;
- }
- catch (Exception ex)
- {
- //handle the exception;
- }
#T#然而,這樣捕獲的WCF異常,卻無法識別DirectoryNotFoundException所傳遞的錯誤信息。尤為嚴重的是這樣的異常處理方式還會導致傳遞消息的通道出現錯誤,當客戶端繼續(xù)調用該服務代理對象的服務操作時,會獲得一個CommunicationObjectFaultedException 異常,無法繼續(xù)使用服務。如果服務被設置為PerSession模式或者Single模式,異常還會導致服務對象被釋放,終止服務。
- [ServiceContract(SessionModeSessionMode = SessionMode.Allowed)]
- public interface IDocumentsExplorerService
- {
- [OperationContract]
- [FaultContract(typeof(DirectoryNotFoundException))]
- DocumentList FetchDocuments(string homeDir);
- }