The Fault Contract sample demonstrates how to communicate error information from a service to a client. The sample is based on the Getting Started, with some additional code added to the service to convert an internal exception to a fault. The client attempts to perform division by zero to force an error condition on the service.

Note

The setup procedure and build instructions for this sample are located at the end of this topic.

The calculator contract has been modified to include a FaultContractAttribute as shown in the following sample code.

C#
[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
[OperationContract]
int Add(int n1, int n2);
[OperationContract]
int Subtract(int n1, int n2);
[OperationContract]
int Multiply(int n1, int n2);
[OperationContract]
[FaultContract(typeof(MathFault))]
int Divide(int n1, int n2);
}

The FaultContractAttribute attribute indicates that the Divide operation may return a fault of type MathFault. A fault can be of any type that can be serialized. In this case, the MathFault is a data contract, as follows:

C#
[DataContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public class MathFault
{
private string operation;
private string problemType; [DataMember]
public string Operation
{
get { return operation; }
set { operation = value; }
} [DataMember]
public string ProblemType
{
get { return problemType; }
set { problemType = value; }
}
}

The Divide method throws a FaultException<TDetail> exception when a divide by zero exception occurs as shown in the following sample code. This exception results in a fault being sent to the client.

C#
public int Divide(int n1, int n2)
{
try
{
return n1 / n2;
}
catch (DivideByZeroException)
{
MathFault mf = new MathFault();
mf.operation = "division";
mf.problemType = "divide by zero";
throw new FaultException<MathFault>(mf);
}
}

The client code forces an error by requesting a division by zero. When you run the sample, the operation requests and responses are displayed in the client console window. You see the division by zero being reported as a fault. Press ENTER in the client window to shut down the client.

console
Add(15,3) = 18
Subtract(145,76) = 69
Multiply(9,81) = 729
FaultException<MathFault>: Math fault while doing division. Problem: divide by zero Press <ENTER> to terminate client.

The client does this by catching the appropriate FaultException<MathFault> exception:

C#
catch (FaultException<MathFault> e)
{
Console.WriteLine("FaultException<MathFault>: Math fault while doing " + e.Detail.operation + ". Problem: " + e.Detail.problemType);
client.Abort();
}

By default, the details of unexpected exceptions are not sent to the client to prevent details of the service implementation from escaping the secure boundary of the service. FaultContract provides a way to describe faults in a contract and mark certain types of exceptions as appropriate for transmission to the client. FaultException<T> provides the run-time mechanism for sending faults to consumers.

However, it is useful to see the internal details of a service failure when debugging. To turn off the secure behavior previously described, you can indicate that the details of every unhandled exception on the server should be included in the fault that is sent to the client. This is accomplished by setting IncludeExceptionDetailInFaults to true. You can either set it in code, or in configuration as shown in the following sample.

XML
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
</serviceBehaviors>
</behaviors>

Further, the behavior must be associated with the service by setting the behaviorConfiguration attribute of the service in the configuration file to "CalculatorServiceBehavior".

To catch such faults on the client, the non-generic FaultException must be caught.

This behavior should only be used for debugging purposes and should never be enabled in production.

To set up, build, and run the sample

  1. Ensure that you have performed the One-Time Setup Procedure for the Windows Communication Foundation Samples.

  2. To build the C# or Visual Basic .NET edition of the solution, follow the instructions in Building the Windows Communication Foundation Samples.

  3. To run the sample in a single- or cross-machine configuration, follow the instructions in Running the Windows Communication Foundation Samples.

Important

The samples may already be installed on your machine. Check for the following (default) directory before continuing.

<InstallDrive>:\WF_WCF_Samples

If this directory does not exist, go to Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4 to download all Windows Communication Foundation (WCF) and WF samples. This sample is located in the following directory.

<InstallDrive>:\WF_WCF_Samples\WCF\Basic\Contract\Service\Faults

WCF: can't catch FaultException(TDetail) - only non-generic FaultException

最后发现,是因为有人在全局的异常处理的地方,实现了IErrorHandler

public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
if(error is FaultException<NameDuplicationFault>) { }
else
{
var faultException = new FaultException(
"Server error. Detail: " + error.Message);
var messageFault = faultException.CreateMessageFault();

fault = Message.CreateMessage(version, messageFault, faultException.Action);
}
}

Fault Contract的更多相关文章

  1. WCF学习之旅—基于Fault Contract 的异常处理(十八)

       WCF学习之旅—WCF中传统的异常处理(十六) WCF学习之旅—基于ServiceDebug的异常处理(十七) 三.基于Fault Contract 的异常处理 第二个示例是通过定制Servic ...

  2. Learning WCF:Fault Handling

    There are two types of Execptions which can be throwed from the WCF service. They are Application ex ...

  3. WCF学习系列三--【WCF Interview Questions – Part 3 翻译系列】

    http://www.topwcftutorials.net/2012/10/wcf-faqs-part3.html WCF Interview Questions – Part 3 This WCF ...

  4. [WCF编程]3.WCF基础

    一.服务 服务是一组公开功能的集合. 服务内部包含了如语言.技术.版本与框架等概念,服务之间的交互只允许使用规定的通信模式 外界客户端并不知道服务内部的实现细节,所以WCF服务通常通过元数据的方式描述 ...

  5. C#进阶系列——DDD领域驱动设计初探(四):WCF搭建

    前言:前面三篇分享了下DDD里面的两个主要特性:聚合和仓储.领域层的搭建基本完成,当然还涉及到领域事件和领域服务的部分,后面再项目搭建的过程中慢慢引入,博主的思路是先将整个架构走通,然后一步一步来添加 ...

  6. WCF

    --http://www.doc88.com/p-699300196010.html ---术语 WCF术语 消息(message) 消息是一个独立的数据单元,它可能由几个部分组成,包括消息正文和消息 ...

  7. WCF初识

    WCF能干什么? 在win32中,应用程序是运行在进程的线程中的,.NET出现之后,出现了AppDomain,其实就相当于在进程和线程之间又又了一层包装层,类似于子进程的概念,在一个进程或者应用程序域 ...

  8. WCF ABC

    参考文献 http://blog.sina.com.cn/s/blog_7358f8b201012pnt.html http://www.cnblogs.com/CodingPerfectWorld/ ...

  9. 跟我一起学WCF(13)——WCF系列总结

    引言 WCF是微软为了实现SOA的框架,它是对微乳之前多种分布式技术的继承和扩展,这些技术包括Enterprise Service..NET Remoting.XML Web Service.MSMQ ...

随机推荐

  1. 前端 CSS的选择器 高级选择器

    高级选择器分为: 后代选择器 儿子选择器 并集选择器 交集选择器 后代选择器 使用空格表示后代选择器.父元素的后代(包括儿子,孙子,重孙子) 后代选择器 在CSS中使用非常频繁 因为HTML元素可以嵌 ...

  2. linux自动化运维工具Ansible saltstack Puppet、Chef、Fabric之间的对比

    发现分布式是一个发展的趋势,无论是大型网站的负载均衡架构还是大数据框架部署,以及云存储计算系统搭建都离不开多台服务器的连续部署和环境搭建. 当我们的基础架构是分散式或者基于云的,并且我们经常需要处理在 ...

  3. 1 Python 新建项目

    1 新建项目->新建Python文件 2导入package 库文件 3 import 类似using #include 4 写完代码编译 默认debug的对象是第一个创建的py文件,后续写的文件 ...

  4. spring-第十六篇之AOP面向切面编程之Spring AOP

    1.上一篇介绍了AspectJ在AOP的简单应用,让我们了解到它的作用就是:开发者无需修改源代码,但又可以为这些组件的方法添加新的功能. AOP的实现可分为两类(根据AOP修改源码的时机划分): 1& ...

  5. ofbiz16.11.04(环境搭建)

    ofbiz16.11.04(环境搭建) 版本说明: ofbiz 16.11.04 下载地址:http://ofbiz.apache.org/download.html gradle 4.9 下载地址: ...

  6. 开发chrome插件(扩展)

    官方文档 https://developer.chrome.com/extensions/getstarted.html [干货]Chrome插件(扩展)开发全攻略 http://blog.haoji ...

  7. 利用反射优化Servlet抽象出父类BaseServlet

    在编写servlet的时候发现每个servlet里面的doPost方法都如: protected void doPost(HttpServletRequest request, HttpServlet ...

  8. 使用myBase Desktop来管理电脑上的资料

    下载链接:下载链接:http://www.wjjsoft.com/download.html 选择自己的操作系统下的myBase Desktop 这里是下载的是安装包,有解压的版本的. 这里就简单介绍 ...

  9. sqli(8)

    第八关:单引号GET盲注 前言:感冒了很有以后摸到靶场,如若隔世....我的天,说不定又有同学要去实习了,再看看我.啧啧啧,神的飞起来.. 盲注需要掌握一些MySQL的相关函数:length(str) ...

  10. 详解webpack4打包--新手入门(填坑)

    注意,这个dev和build好像在哪儿见过??对了, 刚刚才在package.json里配置的“scripts”这一项的值就有“dev”和“build”.对,一点都不错,就是这2个值,这2个值代表的是 ...