There are two types of Execptions which can be throwed from the WCF service. They are Application excepiton and Infrastructure exception.

Handle Application Exception

If we do nothing, a FaultException always be throwed when your WCF service appear any error. For example:

Service:

using Service.Interface;
using Entities;
using System; namespace Service
{
public class PeopleService : IPeopleOperator
{
public void DeletePerson(Person person)
{
Console.WriteLine("Have deleted a person whoes name is:" + person.Name);
}
}
}

Client:

using Entities;
using Service.Interface;
using System;
using System.ServiceModel; namespace Client
{
class Program
{
static void Main(string[] args)
{
using (ChannelFactory<IPeopleOperator> channelFactory = new ChannelFactory<IPeopleOperator>(new WSHttpBinding(),
"http://localhost:9999/PeopleService"))
{
IPeopleOperator proxy = channelFactory.CreateChannel(); Person person = null;
proxy.DeletePerson(person); Console.Read();
}
}
}
}

When you run the Client code:

There is no useful information. We should use Fault Contract. Fault Contract allow developer define error information entity flexible.

Using Fault Contract

Create an Error message container entity

using System.Runtime.Serialization;

namespace Entities
{
[DataContract]
public class ErrorInformation
{
public ErrorInformation(string messages,
string serviceName,
string methodName)
{
Messages = messages;
ServiceName = serviceName;
MethodName = methodName;
} [DataMember]
public string Messages { get; private set; } [DataMember]
public string ServiceName { get; private set; } [DataMember]
public string MethodName { get; private set; }
}
}

Apply FaultContract attribute on the operation of the contract interface

using Entities;
using System.ServiceModel; namespace Service.Interface
{
[ServiceContract(Name = "PeopleOperatorService", Namespace ="http://zzy0471.cnblogs.com")]
public interface IPeopleOperator
{
[FaultContract(typeof(ErrorInformation))]
[OperationContract]
void DeletePerson(Person person);
}
}

Mondify the Service Code

using Service.Interface;
using Entities;
using System;
using System.ServiceModel; namespace Service
{
public class PeopleService : IPeopleOperator
{ public void DeletePerson(Person person)
{
if (person == null)
{
var error = new ErrorInformation("参数person为null",
"PeopleService",
"DeletePerson"); throw new FaultException<ErrorInformation>(error);
}
else
{
Console.WriteLine("Have deleted a person whoes name is:" + person.Name);
}
}
}
}

Mondify the Clinet Code:

using Entities;
using Service.Interface;
using System;
using System.ServiceModel; namespace Client
{
class Program
{
static void Main(string[] args)
{
using (ChannelFactory<IPeopleOperator> channelFactory = new ChannelFactory<IPeopleOperator>(new WSHttpBinding(),
"http://localhost:9999/PeopleService"))
{
IPeopleOperator proxy = channelFactory.CreateChannel(); Person person = null;
try
{
proxy.DeletePerson(person);
}
catch (FaultException<ErrorInformation> fe)
{
Console.WriteLine(fe.Detail.Messages + " in method " + fe.Detail.MethodName + " of service " + fe.Detail.ServiceName);
}
catch(FaultException)
{
Console.WriteLine("Unknow FaultException");
} Console.Read();
}
}
}
}

Handle Infrastructure Exception

Except application exceptions, some Infrastructure Exceptions occasionally occur. For example: communication error, which may occur because of network unavailability, an incorrect address, the host process not running, and so on. The second type of error is related to the state of the proxy

and the channels. So We need some more catch:

catch (CommunicationException ex)
{
Console.WriteLine("Communication error:" + ex.Message);
}
catch(ObjectDisposedException ex)
{
Console.WriteLine("The proxy is closed:" + ex.Message);
}
catch (InvalidOperationException ex)
{
Console.WriteLine("InvalidOperation:" + ex.Message);
}
catch(TimeoutException ex)
{
Console.WriteLine("Timeout:" + ex.Message);
}
catch(Exception)
{
Console.WriteLine("Unknow Infrastructure Exception ");
}

Whole code of client:

using Entities;
using Service.Interface;
using System;
using System.ServiceModel; namespace Client
{
class Program
{
static void Main(string[] args)
{
using (ChannelFactory<IPeopleOperator> channelFactory = new ChannelFactory<IPeopleOperator>(new WSHttpBinding(),
"http://localhost:9999/PeopleService"))
{
IPeopleOperator proxy = channelFactory.CreateChannel(); Person person = null;
try
{
proxy.DeletePerson(person);
} //
// Application Exception
//
catch (FaultException<ErrorInformation> fe)
{
Console.WriteLine(fe.Detail.Messages + " in method " + fe.Detail.MethodName + " of service " + fe.Detail.ServiceName);
}
catch(FaultException)
{
Console.WriteLine("Unknow Application FaultException");
} //
// Infrastructure Exception
//
catch (CommunicationException ex)
{
Console.WriteLine("Communication error:" + ex.Message);
}
catch(ObjectDisposedException ex)
{
Console.WriteLine("The proxy is closed:" + ex.Message);
}
catch (InvalidOperationException ex)
{
Console.WriteLine("InvalidOperation:" + ex.Message);
}
catch(TimeoutException ex)
{
Console.WriteLine("Timeout:" + ex.Message);
}
catch(Exception)
{
Console.WriteLine("Unknow Infrastructure Exception ");
}
Console.Read();
}
}
}
}

That's all.

Download the sourcecode

Learning WCF:Fault Handling的更多相关文章

  1. Learning WCF:Life Cycle of Service instance

    示例代码下载地址:WCFDemo1Day 概述 客户端向WCF服务发出请求后,服务端会实例化一个Service对象(实现了契约接口的对象)用来处理请求,实例化Service对象以及维护其生命周期的方式 ...

  2. Learning WCF:A Simple Demo

    This is a very simple demo which can help you create a wcf applition quickly. Create a Solution Open ...

  3. Learning WCF Chapter1 Hosting a Service in IIS

    How messages reach a service endpoint is a matter of protocols and hosting. IIS can host services ov ...

  4. Learning WCF Chapter1 Generating a Service and Client Proxy

    In the previous lab,you created a service and client from scratch without leveraging the tools avail ...

  5. WCF:为 SharePoint 2010 Business Connectivity Services 构建 WCF Web 服务(第 1 部分,共 4 部分)

    转:http://msdn.microsoft.com/zh-cn/library/gg318615.aspx 摘要:通过此系列文章(共四部分)了解如何在 Microsoft SharePoint F ...

  6. Learning WCF 书中的代码示例下载地址

    Learning WCF Download Example Code 第一个压缩文件LearningWCF.zip是VS2005创建的项目,不要下载这个. 建议下载VS2008版的,以及Media

  7. Multiple address space mapping technique for shared memory wherein a processor operates a fault handling routine upon a translator miss

    Virtual addresses from multiple address spaces are translated to real addresses in main memory by ge ...

  8. Learning WCF Chapter1 Exposing Multiple Service Endpoints

    So far in this chapter,I have shown you different ways to create services,how to expose a service en ...

  9. Portal:Machine learning机器学习:门户

    Machine learning Machine learning is a scientific discipline that explores the construction and stud ...

随机推荐

  1. Dom文本应用-表格隔行间亮样式

    效果:  隔行一个颜色,鼠标移上去,被选中的那一行就变颜色,其次,鼠标离开其区域,颜色又变回原来的颜色. 一.表格隔行间亮样式-HTML代码 首先我们要有个表格 <table id='tab1' ...

  2. 小事牛刀之——python做文件对比

    使用python对比filename1和filenam2的差异,并将差异写入到filename3中. #!/usr/bin/env python # -*- coding: utf-8 -*- # @ ...

  3. centos7-内核版本降级

    1. 查看内核版本参考命令: [root@localhost ~]# cat /etc/redhat-release CentOS Linux release 7.3.1611 (Core) [roo ...

  4. mysql5.5升级到5.7

    一.首先把mysql服务停止,复制mysql5.5中的data文件夹中的内容(你需要的数据库),放在mysql5.7的data文件夹中; 二.启动切换mysql5.7版本,(我这用的是phpwamp, ...

  5. reentrantlocklock实现有界队列

    今天找synchronize和reentrantlock区别的时候,发现有个使用reentrantlock中的condition实现有界队列,感觉挺有趣的,自己顺手敲了一遍 class Queue{ ...

  6. python note 04 list的应用及元组

    1,昨日内容 ascii:字母,数字,特殊字符:1个字节,8位 Unicode:16位 两个字节 升级 32 位 四个字节 utf-8:最少一个字节 8位表示. 英文字母 8位 1个字节 欧洲16位, ...

  7. 微信小程序之 -----事件

    事件分类      1. 冒泡事件:     当一个组件上的事件被触发后,该事件会向父节点传递.      2. 非冒泡事件:   当一个组件上的事件被触发后,该事件不会向父节点传递.   常见的冒泡 ...

  8. 带标签的循环语句、switch

    今天继续更新,控制流程的剩余部分内容,带标签的循环语句中的continue/break 的使用方法,以及switch关键字的使用方法.例1:带标签的continue/break.package com ...

  9. centOS7搭建nexus私服

    1.保证JDK,MAVEN已安装,firewalld服务安装 PS:yum install firewalld 2.官网下载:https://www.sonatype.com/download-oss ...

  10. windows下 zookeeper

    1.zookeeper的安装和配置 下载:http://zookeeper.apache.org/releases.html 把conf目录下的zoo_sample.cfg改名成zoo.cfg,这里我 ...