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. 最简单的cmd命令行取得系统路径和python的安装路径(适用于winxp.win7和win10)

    @echo off::pip install seleniumpython -c"import sys;print(sys.prefix)" >temp.txtfor /f ...

  2. python大法好——模块(内置模块未完)

    模块 模块是非常简单的Python文件,单个Python文件就是一个模块,两个文件就是两个模块. Python模块有什么作用? 1.模块内有许多函数方法,利用这些方法可以更简单的完成许多工作.2.模块 ...

  3. spring jdbc学习1

    1.queryForObject - 其中的 RowMapper 指定如何去映射结果集的行, 常用的实现类为 BeanPropertyRowMapper - 使用 SQL 中列的别名完成列名和类的属性 ...

  4. Python 高阶函数map(),filter(),reduce()

    map()函数,接收两个参数,一个是函数,一个是序列,map()把传入的函数依次作用于序列的每个元素,并把结果作为新的序列返回: aa = [1, 2, 3, 4, 5] print("ma ...

  5. python装饰器补漏

    以前写过一篇装饰器文章,觉得少了点东西,今天特来补上,也就是带参数的装饰器,上篇文章写的不严谨 def logger(logs=""): def outer(f): def inn ...

  6. Spring中@相关注解的意义

    1.@controller 控制器(注入服务) 用于标注控制层,相当于struts中的action层 2.@service 服务(注入dao) 用于标注服务层,主要用来进行业务的逻辑处理 3.@rep ...

  7. Java学习08 (第一遍) - SpringMVC

    写一下午的好多居然丢失...自动保存也只是保存丢失后的 那就不多写了,简单写: Spring:(自己画的) 官网的: 写一个Spring的例子: Eclipse http://repo.spring. ...

  8. java十进制转换成二进制数

    牢记这些呀,特别常用! 1.十进制转成二进制 String s = Integer.toBinaryString(n)  //将十进制数转成字符串,例如n=5 ,s = "101" ...

  9. 36. Valid Sudoku 判断九九有效的数独

    [抄题]: Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according ...

  10. 508. Most Frequent Subtree Sum 最频繁的子树和

    [抄题]: Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum ...