關(guān)于WCF異常處理解決方案總結(jié)
異常處理在我們的程序中是不可缺少的,異??梢苑答佄覀冃畔?,如果還不知道WCF異常的朋友請(qǐng)看下面我為大家介紹一下。異常消息與特定技術(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ǔ)這一缺陷,無(wú)法識(shí)別的WCF異常均當(dāng)作為FaultException異常對(duì)象,因此,客戶端可以捕獲FaultException或者Exception異常:
- catch (FaultException ex)
- {
- //handle the exception;
- }
- catch (Exception ex)
- {
- //handle the exception;
- }
#T#然而,這樣捕獲的異常,卻無(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ù)。WCF并不推薦在應(yīng)用程序域中創(chuàng)建多個(gè)ServiceHost實(shí)例。如果要托管多個(gè)服務(wù),完全可以在一個(gè)宿主中通過(guò)多個(gè)Endpoint公開(kāi)多個(gè)WCF服務(wù)。由于應(yīng)用程序域?qū)Π踩M(jìn)行了隔離,如果需要提供不同的安全上下文,則有必要?jiǎng)?chuàng)建多個(gè)ServiceHost實(shí)例。