WCF中的异常处理
为了弥补这一缺陷,WCF会将无法识别的异常均当作为FaultException异常对象,因此,客户端可以捕获FaultException或者Exception异常:
catch (FaultException ex)
{
//handle the exception;
}
catch (Exception ex)
{
//handle the exception;
}
然而,这样捕获的异常,却无法识别DirectoryNotFoundException所传递的错误信息。尤为严重的是这样的异常处理方式还会导致传递消息的通道出现错误,当客户端继续调用该服务代理对象的服务操作时,会获得一个CommunicationObjectFaultedException异常,无法继续使用服务。如果服务被设置为PerSession模式或者Single模式,异常还会导致服务对象被释放,终止服务。
WCF为异常处理专门提供了FaultContract特性,它可以被应用到服务操作上,指明操作可能会抛出的异常类型。例如前面的服务契约就可以修改为:
[ServiceContract(SessionMode = SessionMode.Allowed)]
public interface IDocumentsExplorerService
{
[OperationContract]
[FaultContract(typeof(DirectoryNotFoundException))]
DocumentList FetchDocuments(string homeDir);
}
然而,即使通过FaultContract指定了操作要抛出的异常,然而如果服务抛出的异常并非FaultException或者FaultException<T>异常,同样会导致通道发生错误。因此在服务实现中,正确的实现应该如下:
public class DocumentsExplorerService : IDocumentsExplorerService,IDisposable
{
public DocumentList FetchDocuments(string homeDir)
{
//Some Codes
if (Directory.Exists(homeDir))
{
//Fetch documents according to homedir
}
else
{
DirectoryNotFoundException exception = new DirectoryNotFoundException();
throw new FaultException<DirectoryNotFoundException>(exception,
new FaultReason(string.Format("Directory {0} is not found.", homeDir)));
}
}
}
0
相关文章