為你解決WCF異常問題
WCF還是比較常用的,于是我研究了一下WCF,在這里拿出來和大家分享一下,希望對大家有用。異常消息與特定技術(shù)有關(guān),.NET異常同樣如此,因而WCF并不支持傳統(tǒng)的異常處理方式。如果在WCF服務(wù)中采用傳統(tǒng)的方式處理異常,由于異常消息不能被序列化,因而客戶端無法收到服務(wù)拋出的WCF異常,例如這樣的服務(wù)設(shè)計:
- [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.");
- }
- }
則客戶端在調(diào)用如上的服務(wù)操作時,如果采用如下的捕獲方式是無法獲取該WCF異常的:
- catch (DirectoryNotFoundException ex)
- {
- //handle the exception;
- }
為了彌補這一缺陷,WCF會將無法識別的異常均當(dāng)作為FaultException異常對象,因此,客戶端可以捕獲FaultException或者Exception異常:
- catch (FaultException ex)
- {
- //handle the exception;
- }
- catch (Exception ex)
- {
- //handle the exception;
- }
#T#然而,這樣捕獲的WCF異常,卻無法識別DirectoryNotFoundException所傳遞的錯誤信息。尤為嚴(yán)重的是這樣的異常處理方式還會導(dǎo)致傳遞消息的通道出現(xiàn)錯誤,當(dāng)客戶端繼續(xù)調(diào)用該服務(wù)代理對象的服務(wù)操作時,會獲得一個CommunicationObjectFaultedException 異常,無法繼續(xù)使用服務(wù)。如果服務(wù)被設(shè)置為PerSession模式或者Single模式,異常還會導(dǎo)致服務(wù)對象被釋放,終止服務(wù)。
- [ServiceContract(SessionModeSessionMode = SessionMode.Allowed)]
- public interface IDocumentsExplorerService
- {
- [OperationContract]
- [FaultContract(typeof(DirectoryNotFoundException))]
- DocumentList FetchDocuments(string homeDir);
- }