WCF 服务有两种方式支持异常处理:
1. 在 hosts .config 文件中将 serviceDebug.includeExceptionDetailInFaults 属性定义为“true” 2. 在服务类上将 includeExceptionDetailInFaults 属性定义为“true”。
例子:
配置文件解决方案:
<behaviors>
<serviceBehaviors>
<behavior name=”ServiceBehavior”>
<serviceMetadata httpGetEnabled=”true”/>
<serviceDebug includeExceptionDetailInFaults=”true”/>
</behavior>
</serviceBehaviors>
</behaviors>
归因类解决方案:
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
public class CustomersService : ICustomersService
{
private CustomerDetail customerDetail = null;
… ETC
抛出异常 将 includeExceptionDetailInFaults 设置为 true 是您在 WCF 中支持异常的第一步。
下一步是让您的服务抛出 FaultException 异常(System.ServiceModel.FaultException 命名空间中的一个类)。请注意,当您希望从 WCF 主机向 WCF 客户端抛出异常时,不能期望简单地使用典型的 Exception 类。要在 WCF 绑定上引发异常,您需要使用 FaultException 类。
抛出 FaultException 示例:
try
{
//Try to do stuff
}
catch
{
throw new FaultException(“Full ruckus!”);
}
捕获 FaultException 示例:
现在 WCF 客户端可以捕获 FaultException...</p>
try
{
//Client calls services off the proxy
}
catch(FaultException fa)
{
MessageBox.Show(fa.Message);
}
区分错误异常
的类型 FaultException 类是 WCF 异常的通用类。为了确定发生什么类型的 FaultExceptions,您可以使用 FaultCode 类。在 WCF 服务上,FaultCode 实现将如下所示:
try
{
//Connect to a database
}
catch
{
throw new FaultException(“Full ruckus!”, new FaultCode(“DBConnection”));
}
在 WCF 客户端上,FaultCode 实现将如下所示:
try
{
//Call services via the proxy
}
catch(FaultException fa)
{
switch(fa.Code.Name)
{
case “DBConnection”:
MessageBox.Show(“Cannot connect to database!”);
break;
default:
MessageBox.Show(“fa.message”);
break;
}
}
有关更多信息,您可以查看此处和此处