为你解决WCF异常问题

WCF还是比较常用的,于是我研究了一下WCF,在这里拿出来和大家分享一下,希望对大家有用。异常消息与特定技术有关,.NET异常同样如此,因而WCF并不支持传统的异常处理方式。如果在WCF服务中采用传统的方式处理异常,由于异常消息不能被序列化,因而客户端无法收到服务抛出的WCF异常,例如这样的服务设计:

 
 
  1. [ServiceContract(SessionModeSessionMode = SessionMode.Allowed)]   
  2. public interface IDocumentsExplorerService   
  3. {   
  4. [OperationContract]   
  5. DocumentList FetchDocuments(string homeDir);   
  6. }   
  7. [ServiceBehavior(InstanceContextModeInstanceContextMode=InstanceContextMode.Single)]   
  8. public class DocumentsExplorerService : IDocumentsExplorerService,IDisposable   
  9. {   
  10. public DocumentList FetchDocuments(string homeDir)   
  11. {   
  12. //Some Codes   
  13.  
  14. if (Directory.Exists(homeDir))   
  15. {   
  16. //Fetch documents according to homedir   
  17. }   
  18. else   
  19. {   
  20. throw new DirectoryNotFoundException(   
  21. string.Format("Directory {0} is not found.",homeDir));   
  22. }   
  23. }   
  24. public void Dispose()   
  25. {   
  26. Console.WriteLine("The service had been disposed.");   
  27. }   
  28. }   

则客户端在调用如上的服务操作时,如果采用如下的捕获方式是无法获取该WCF异常的:

 
 
  1. catch (DirectoryNotFoundException ex)   
  2. {   
  3. //handle the exception;   
  4. }   

为了弥补这一缺陷,WCF会将无法识别的异常均当作为FaultException异常对象,因此,客户端可以捕获FaultException或者Exception异常:

 
 
  1. catch (FaultException ex)   
  2. {   
  3. //handle the exception;   
  4. }   
  5. catch (Exception ex)   
  6. {   
  7. //handle the exception;   
  8. }  

#T#然而,这样捕获的WCF异常,却无法识别DirectoryNotFoundException所传递的错误信息。尤为严重的是这样的异常处理方式还会导致传递消息的通道出现错误,当客户端继续调用该服务代理对象的服务操作时,会获得一个CommunicationObjectFaultedException 异常,无法继续使用服务。如果服务被设置为PerSession模式或者Single模式,异常还会导致服务对象被释放,终止服务。

 
 
  1. [ServiceContract(SessionModeSessionMode = SessionMode.Allowed)]   
  2. public interface IDocumentsExplorerService   
  3. {   
  4. [OperationContract]   
  5. [FaultContract(typeof(DirectoryNotFoundException))]   
  6. DocumentList FetchDocuments(string homeDir);   
  7. }   
THE END