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