WCF中的异常处理2010-07-28 cnblogs 张逸异常消息与特定技术有关,.NET异常同样如此,因而WCF并不支持传统的异常处理方式。如果在WCF服务中采用传统的方式处理异常,由于异常消息不能被序列化,因而客户端无法收到服务抛出的异常,例如这样的服务设计:[ServiceContract(SessionMode = SessionMode.Allowed)] public interface IDocumentsExplorerService { [OperationContract] DocumentList FetchDocuments(string homeDir); } [ServiceBehavior(InstanceContextMode=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."); } }则客户端在调用如上的服务操作时,如果采用如下的捕获方式是无法获取该异常的:catch (DirectoryNotFoundException ex) { //handle the exception; }为了弥补这一缺陷,WCF会将无法识别的异常均当作为FaultException异常对象,因此,客户端可以捕获FaultException或者Exception异常:catch (FaultException ex) { //handle the exception; } catch (Exception ex) { //handle the exception; }