WCF中的异常处理

异常消息与特定技术有关,.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;
}

然而,这样捕获的异常,却无法识别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)));
    }
}
}

我们可以将服务所要抛出的异常类型作为FaultException<T>的类型参数,然后创建一个FaultReason对象用以传递错误消息。客户端在调用服务代理对象时,可以捕获FaultException< DirectoryNotFoundException>异常,并且该异常不会使得通道发生错误,并且客户端可以继续使用该服务代理对象。即使服务为PerCall服务,客户端仍然可以继续调用服务操作。如果服务为Session服务或Singleton服务,那么即使发生了异常,服务对象也不会被终结。

如果只是为了让客户端获得异常消息,即使不施加FaultContract特性,或者抛出非FaultException异常,我们也可以通过ServiceBehavior特性,将服务的IncludeExceptionDetailInFaults设置为true(默认为false),此时,客户端可以捕获抛出的非FaultException异常信息,但该异常仍然会导致通道出现错误。

但是,在发布服务与部署服务时,我们应避免将服务的IncludeExceptionDetailInFaults设置为true。

如果不希望使用FaultContract,同时又要保证服务抛出的异常能够被客户端捕获,并且不会导致通道错误,我们还可以通过错误处理扩展的方式实现。此时,我们可以将服务本身作为错误处理对象,令其实现System.ServiceModel.Dispatcher.IErrorHandler接口:
public class DocumentsExplorerService : IDocumentsExplorerService,IErrorHandler, IDisposable
{…}

在该接口的ProvideFault()方法中,可以将非FaultContract异常提升为FaultContract<T>异常,例如将DirectoryNotFoundException异常提升为FaultExceptino<DirectoryNotFoundException>异常:
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
    if (error is DirectoryNotFoundException)
    {
        FaultException<DirectoryNotFoundException> faultException = new FaultException<DirectoryNotFoundException>(
            new DirectoryNotFoundException(), new FaultReason(error.Message));
        MessageFault messageFault = faultException.CreateMessageFault();
        fault = Message.CreateMessage(version,messageFault,faultException.Action);
    }
}

而在该接口的HandleError()方法中,则可以处理异常错误,例如记录日志。

要使得错误处理扩展生效,还需要向服务通道安装错误处理扩展。方法是让服务类实现System.ServiceModel.Description.IServiceBehavior接口:
public class DocumentsExplorerService : IDocumentsExplorerService,IErrorHandler,IServiceBehavior,IDisposable
{…}

然后在ApplyDispatchBehavior()方法中安装错误处理扩展:
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
    foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
    {
        dispatcher.ErrorHandlers.Add(this);
    }
}

通过这样的处理,即使服务抛出的异常为DirectoryNotFoundException异常,并且在服务契约中没有通过FaultContract特性指定该异常,客户端同样能够获得异常的错误信息,且该异常不会导致通道发生错误,客户端可以继续调用服务代理对象的操作。

本文已在IT168发表:http://tech.it168.com/msoft/2007-12-03/200712031939709.shtml

posted on 2007-12-24 10:02 张逸 阅读(2016) 评论(8)  编辑 收藏 所属分类: WCF Tips

评论

#1楼  2007-12-24 10:46 非我      

不错不错,学习了   回复  引用  查看    

#2楼  2007-12-24 11:14 d [未注册用户]

请问,如何设置wcf,才能调用wcf服务的时候,看到方法的注释?   回复  引用    

#3楼  2007-12-24 11:50 Elviss [未注册用户]

楼主,你的书什么时候才能出呀?等了好久了!   回复  引用    

#4楼  2007-12-24 15:19 qqq [未注册用户]

我开始学习WCF就是看LZ的blog的,关注、学习、再学习   回复  引用    

#5楼  2007-12-24 16:28 王伶 [未注册用户]

我总是担心会少看了你写的一些东西,还有你的书到底什么时候才有阿   回复  引用    

#6楼  2007-12-24 17:11 相濡以沫      

学习,学习,好好学习   回复  引用  查看    

#7楼 [楼主] 2007-12-26 11:41 Bruce Zhang      

@Elviss
@王伶
问了出版社,在春节前肯定能出版。   回复  引用  查看    

#8楼  2007-12-31 20:57 金钱豹 [未注册用户]

到时出版了麻烦通知下哦!我的MSN laserhz@hotmail.com
非常感谢老师能翻译这么好的书啊!
Juval Lowy 的书太经典了,他的一本<<.NET组件编程>>使我拜读后就茅塞顿开!   回复  引用    

导航

公告

logo.gif
我的著作与译作

《软件设计精要与模式》

《WCF服务编程》

MVP_Horizontal_BlueOnly.png

From 03-03-2006
Counter: site stats

与我联系

常用链接

我参加的小组

我参与的团队

随笔分类(244)

随笔档案(235)

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜