我的WCF之旅(10):如何在WCF进行Exception Handling-程序员宅基地

技术标签: 网络  runtime  

在任何Application的开发中,对不可预知的异常进行troubleshooting时,异常处理显得尤为重要。对于一般的.NET系统来说,我们简单地借助try/catch可以很容易地实现这一功能。但是对于 一个分布式的环境来说,异常处理就没有那么简单了。按照面向服务的原则,我们把一些可复用的业务逻辑以Service的形式实现,各个Service处于一个自治的环境中,一个Service需要和另一个Service进行交互,只需要获得该Service的描述(Description)就可以了(比如WSDL,Schema和Strategy)。借助标准的、平台无关的通信构架,各个Service之间通过标准的Soap Message进行交互。Service Description、Standard Communication Infrastructure、Soap Message based Communication促使各Service以松耦合的方式结合在一起。但是由于各个Service是自治的,如果一个Service调用另一个Service,在服务提供方抛出的Exception必须被封装在Soap Message中,方能被处于另一方的服务的使用者获得、从而进行合理的处理。下面我们结合一个简单的Sample来简单地介绍我们可以通过哪些方式在WCF中进行Exception Handling。

一、传统的Exception Handling

我们沿用我们一直使用的Calculator的例子和简单的4层构架:


1.    Service Contract- Artech.ExceptionHandling.Contract

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;

namespace Artech.ExceptionHandling.Contract
ExpandedBlockStart.gif {
    [ServiceContract]
     public  interface ICalculator
ExpandedSubBlockStart.gif    {
        [OperationContract]
         double Divide( double x,  double y);
    }
}

定义了一个单一的进行除法运算的Operation。

2.    Service:Artech.ExceptionHandling.Service. CalculatorService

using System;
using System.Collections.Generic;
using System.Text;
using Artech.ExceptionHandling.Contract;

namespace Artech.ExceptionHandling.Service
ExpandedBlockStart.gif {
     public  class CalculatorService:ICalculator
ExpandedSubBlockStart.gif    {
ContractedSubBlock.gif         ICalculator Members
    }
}

如果被除数是零,抛出一个DivideByZeroException Exception。

3.    Service Hosting

Configuration:

<? xml version="1.0" encoding="utf-8"  ?>
< configuration >
     < system .serviceModel >
         < behaviors >
             < serviceBehaviors >
                 < behavior  name ="calculatorServiceBehavior" >
                     < serviceMetadata  httpGetEnabled ="true"   />
                 </ behavior >
             </ serviceBehaviors >
         </ behaviors >
         < services >
             < service  behaviorConfiguration ="calculatorServiceBehavior"  name ="Artech.ExceptionHandling.Service.CalculatorService" >
                 < endpoint  binding ="basicHttpBinding"  bindingConfiguration =""  contract ="Artech.ExceptionHandling.Contract.ICalculator"   />
                 < host >
                     < baseAddresses >
                         < add  baseAddress ="http://localhost:8888/Calculator"   />
                     </ baseAddresses >
                 </ host >
             </ service >
         </ services >
     </ system.serviceModel >
</ configuration >

Program

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using Artech.ExceptionHandling.Service;

namespace Artech.ExceptionHandling.Hosting
ExpandedBlockStart.gif {
     class Program
ExpandedSubBlockStart.gif    {
         static  void Main( string[] args)
ExpandedSubBlockStart.gif        {
             using (ServiceHost calculatorHost =  new ServiceHost( typeof(CalculatorService)))
ExpandedSubBlockStart.gif            {
                calculatorHost.Opened +=  delegate
ExpandedSubBlockStart.gif                {
                    Console.WriteLine("The Calculator service has begun to listen via the address:{0}", calculatorHost.BaseAddresses[0]);
                };
                calculatorHost.Open();
                Console.Read();
            }
        }
    }
}

4.    Client

Configuration:

<? xml version="1.0" encoding="utf-8"  ?>
< configuration >
     < system .serviceModel >
           < client >
             < endpoint  address =http://localhost:8888/Calculator  binding ="basicHttpBinding"  contract ="Artech.ExceptionHandling.Contract.ICalculator"
                name
="defualtEndpoint"   />
         </ client >
     </ system.serviceModel >
</ configuration >

Program

using System;
using System.Collections.Generic;
using System.Text;
using Artech.ExceptionHandling.Contract;
using System.ServiceModel;

namespace Artech.ExceptionHandling.Client
ExpandedBlockStart.gif {
     class Program
ExpandedSubBlockStart.gif    {
         static  void Main( string[] args)
ExpandedSubBlockStart.gif        {
            ChannelFactory<ICalculator> calculatorFactory =  new ChannelFactory<ICalculator>("defualtEndpoint");
            ICalculator calculator = calculatorFactory.CreateChannel();
             try
ExpandedSubBlockStart.gif            {
                Console.WriteLine("Try to invoke Divide method");
                Console.WriteLine("x / y =  {2} when x = {0} and y = {1}", 2, 0, calculator.Divide(2,0));
            }
             catch (Exception ex)
ExpandedSubBlockStart.gif            {
                Console.WriteLine("An Exception is thrown.\n\tException Type:{0}\n\tError Message:{1}", ex.GetType(), ex.Message);
            }
            Console.Read();
        }
    }
}

把Service调用放在一个try/catch block中,看看Service端抛出的DivideByZeroException Exception能否被Catch。

我们运行这个程序,看看Client有怎样的输出:


我们发现Client catch住的不是我们Service端真正抛出的DivideByZeroException Exception,而是一个比较General的FaultException。Error message也是很general:

"The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs."

二、基于ServiceDebug的Exception Handling

很显然Client端Catch住的Exception对我们进行troubleshooting。为了利于我们进行有效的Debug,WCF提供了ServiceDebug Service Behavior。我们通过includeExceptionDetailInFaults属性设为true,那么如果Service抛出Exception,WCF会简单得包装这个Exception并把它置于Soap中Response到Service的访问者。介于此,我修改了Hosting的Configuration:

<? xml version="1.0" encoding="utf-8"  ?>
< configuration >
     < system .serviceModel >
         < behaviors >
             < serviceBehaviors >
                 < behavior  name ="calculatorServiceBehavior" >
                     < serviceMetadata  httpGetEnabled ="true"   />
                     < serviceDebug  includeExceptionDetailInFaults ="true"   />
                 </ behavior >
             </ serviceBehaviors >
         </ behaviors >
         < services >
             < service  behaviorConfiguration ="calculatorServiceBehavior"  name ="Artech.ExceptionHandling.Service.CalculatorService" >
                 < endpoint  binding ="basicHttpBinding"  bindingConfiguration =""  contract ="Artech.ExceptionHandling.Contract.ICalculator"   />
                 < host >
                     < baseAddresses >
                         < add  baseAddress ="http://localhost:8888/Calculator"   />
                     </ baseAddresses >
                 </ host >
             </ service >
         </ services >
     </ system.serviceModel >
</ configuration >

现在再次运行程序,看看现在的运行结果:


可以看到我们我们Catch的是一个FaultException< ExceptionDetail>Type的Exception,不是原来的FaultException。该Exception的Detail属性就是Service抛出的DivideByZeroException Exception。有兴趣的人可以自己测试一下。而且我们在Service端指定的Error Message也被Client获得。这种方式的Exception Handling方式确实比上面一种具有很强的指示性,对我们进行Debug确实很有帮助。但是这种方式确实不能正式用于我们最终发布的版本中,因为它会把Exception所有的信息返回到Client端,很容易泄露一些很敏感的信息。这也正是WCF把这个列入ServiceDebug Service Behavior的原因。

三、基于Fault Contract 的Exception Handling

既然上面通过定制ServiceDebug只能用于Debug阶段。我们必须寻求另外一种Exception Handling的方式。那就是我们现在将要介绍的基于FaultContract的解决方案。我们知道WCF采用一种基于Contract,Contract定义了进行交互的双方进行消息交换所遵循的准则和规范。Service Contract定义了包含了所有Operation的Service的接口,Data Contract定义了交互的数据的结构,而FaultContract实际上定义需要再双方之间进行交互的了异常、错误的表示。我们现在来看看如何来使用基于FaultContract的Exception Handling。

我们首先来定义一个表示Fault的类:MathError。考虑到这个类需要在Service 和Client使用,我把它定义在Artech.ExceptionHandling.Contract中:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace Artech.ExceptionHandling.Contract
ExpandedBlockStart.gif {
    [DataContract]
    public   class MathError
ExpandedSubBlockStart.gif    {
         private  string _operation;
         private  string _errorMessage;

        public MathError( string operation,  string errorMessage)
ExpandedSubBlockStart.gif       {
            this._operation = operation;
            this._errorMessage = errorMessage;
       }

        [DataMember]
         public  string Operation
ExpandedSubBlockStart.gif        {
ExpandedSubBlockStart.gif             get {  return _operation; }
ExpandedSubBlockStart.gif             set { _operation = value; }
        }

       [DataMember]
         public  string ErrorMessage
ExpandedSubBlockStart.gif        {
ExpandedSubBlockStart.gif             get {  return _errorMessage; }
ExpandedSubBlockStart.gif             set { _errorMessage = value; }
        }
    }
}

在MathError中定义了两个成员:表示出错操作的Operation和出错信息的ErrorMessage。由于该类的对象需要在Endpoint之间传递,所以必须是可序列化的,在WCF中,我们一般用两个不同的Serializer实现Object和XML的Serialization和Deserialization:Datacontract Serializer和XML Serializer。而对于Fault,只能使用前者。

定义了MathError,我们需要通过FaultContract将其运用到Service Contract中制定的Operation上面,我们通过下面的方式来实现:

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;

namespace Artech.ExceptionHandling.Contract
ExpandedBlockStart.gif {
    [ServiceContract]
     public  interface ICalculator
ExpandedSubBlockStart.gif    {
        [OperationContract]
        [FaultContract( typeof(MathError))]
         double Divide( double x,  double y);
    }
}

我们在Divide上运用了FaultContract,并指定了封装了Fault对应的类型,那么最终这个基于MathError类型的FaultContract会被写入Service Description中,Client通过获取该Service Description(一般是获取WSDL),它就被识别它,就会将从接收到的Soap中对该Fault的XML Mapping到具体的MathError类型。

接着我们在Service Implementation中以抛出Exception的方式植入这个MathError对象:

using System;
using System.Collections.Generic;
using System.Text;
using Artech.ExceptionHandling.Contract;
using System.ServiceModel;

namespace Artech.ExceptionHandling.Service
ExpandedBlockStart.gif {
     public  class CalculatorService:ICalculator
ExpandedSubBlockStart.gif    {
ContractedSubBlock.gif         ICalculator Members
    }
}

在被除数为0的时候,抛出FaultException<MathError> Exception,并指定具体的MathError对象,以及一个FaultCode(一般指明出错的来源)和FaultReason(出错的原因)。

我们现在先不修改Client的Exception Handling的相关代码,先运行Hosting,看看WSDL中什么特别之处:


通过上面的Screenshot,我们可以看到,在PortType section中的Divide Operation定义了Message为tns:ICalculator_Divide_MathErrorFault_FaultMessage 的<wsdl:fault>节点。通过查看Message Section,我们发现tns:ICalculator_Divide_MathErrorFault_FaultMessage的Element为q1:MathError,该q1:MathError type实际上是被定义在一个XSD中,其Uri为http://localhost:8888/Calculator?xsd=xsd2,我们定义的所有DataContract都在其中,下面的整个内容:

<? xml version="1.0" encoding="utf-8" ?>
< xs:schema  elementFormDefault ="qualified"  targetNamespace ="http://schemas.datacontract.org/2004/07/Artech.ExceptionHandling.Contract"  xmlns:xs ="http://www.w3.org/2001/XMLSchema"  xmlns:tns ="http://schemas.datacontract.org/2004/07/Artech.ExceptionHandling.Contract" >
   < xs:complexType  name ="MathError" >
     < xs:sequence >
       < xs:element  minOccurs ="0"  name ="ErrorMessage"  nillable ="true"  type ="xs:string" />
       < xs:element  minOccurs ="0"  name ="Operation"  nillable ="true"  type ="xs:string" />
     </ xs:sequence >
   </ xs:complexType >
   < xs:element  name ="MathError"  nillable ="true"  type ="tns:MathError" />
</ xs:schema >

弄清楚了Fault在WSDL中表示后,我们来修改我们Client端的代码,来有效地进行Exception Handling:

static  void Main( string[] args)
ExpandedBlockStart.gif         {
            ChannelFactory<ICalculator> calculatorFactory =  new ChannelFactory<ICalculator>("defualtEndpoint");
            ICalculator calculator = calculatorFactory.CreateChannel();
             try
ExpandedSubBlockStart.gif            {
                Console.WriteLine("Try to invoke Divide method");
                Console.WriteLine("x / y =  {2} when x = {0} and y = {1}", 2, 0, calculator.Divide(2, 0));
            }
             catch (FaultException<MathError> ex)
ExpandedSubBlockStart.gif            {
                MathError error = ex.Detail;
                Console.WriteLine("An Fault is thrown.\n\tFault code:{0}\n\tFault Reason:{1}\n\tOperation:{2}\n\tMessage:{3}", ex.Code, ex.Reason, error.Operation, error.ErrorMessage);
            }

             catch (Exception ex)
ExpandedSubBlockStart.gif            {
                Console.WriteLine("An Exception is thrown.\n\tException Type:{0}\n\tError Message:{1}", ex.GetType(), ex.Message);
            }
            Console.Read();
        }

下面是运行后的输出结果:


WCF相关内容:
[原创]我的WCF之旅(1):创建一个简单的WCF程序
[原创]我的WCF之旅(2):Endpoint Overview
[原创]我的WCF之旅(3):在WCF中实现双向通信(Bi-directional Communication)
[原创]我的WCF之旅(4):WCF中的序列化(Serialization)- Part I
[原创]我的WCF之旅(4):WCF中的序列化(Serialization)- Part II
[原创]我的WCF之旅(5):Service Contract中的重载(Overloading)
[原创]我的WCF之旅(6):在Winform Application中调用Duplex Service出现TimeoutException的原因和解决方案
[原创]我的WCF之旅(7):面向服务架构(SOA)和面向对象编程(OOP)的结合——如何实现Service Contract的继承
[原创]我的WCF之旅(8):WCF中的Session和Instancing Management
[原创]我的WCF之旅(9):如何在WCF中使用tcpTrace来进行Soap Trace
[原创]我的WCF之旅(10): 如何在WCF进行Exception Handling
[原创]我的WCF之旅(11):再谈WCF的双向通讯-基于Http的双向通讯 V.S. 基于TCP的双向通讯

[原创]我的WCF之旅(12):使用MSMQ进行Reliable Messaging
[原创]我的WCF之旅(13):创建基于MSMQ的Responsive Service


作者:蒋金楠
微信公众账号:大内老A
微博: www.weibo.com/artech
如果你想及时得到个人撰写文章以及著作的消息推送,或者想看看个人推荐的技术资料,可以扫描左边二维码(或者长按识别二维码)关注个人公众号(原来公众帐号 蒋金楠的自媒体将会停用)。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_34309543/article/details/90334699

智能推荐

获取大于等于一个整数的最小2次幂算法(HashMap#tableSizeFor)_整数 最小的2的几次方-程序员宅基地

文章浏览阅读2w次,点赞51次,收藏33次。一、需求给定一个整数,返回大于等于该整数的最小2次幂(2的乘方)。例: 输入 输出 -1 1 1 1 3 4 9 16 15 16二、分析当遇到这个需求的时候,我们可能会很容易想到一个"笨"办法:..._整数 最小的2的几次方

Linux 中 ss 命令的使用实例_ss@,,x,, 0-程序员宅基地

文章浏览阅读865次。选项,以防止命令将 IP 地址解析为主机名。如果只想在命令的输出中显示 unix套接字 连接,可以使用。不带任何选项,用来显示已建立连接的所有套接字的列表。如果只想在命令的输出中显示 tcp 连接,可以使用。如果只想在命令的输出中显示 udp 连接,可以使用。如果不想将ip地址解析为主机名称,可以使用。如果要取消命令输出中的标题行,可以使用。如果只想显示被侦听的套接字,可以使用。如果只想显示ipv4侦听的,可以使用。如果只想显示ipv6侦听的,可以使用。_ss@,,x,, 0

conda activate qiuqiu出现不存在activate_commandnotfounderror: 'activate-程序员宅基地

文章浏览阅读568次。CommandNotFoundError: 'activate'_commandnotfounderror: 'activate

Kafka 实战 - Windows10安装Kafka_win10安装部署kafka-程序员宅基地

文章浏览阅读426次,点赞10次,收藏19次。完成以上步骤后,您已在 Windows 10 上成功安装并验证了 Apache Kafka。在生产环境中,通常会将 Kafka 与外部 ZooKeeper 集群配合使用,并考虑配置安全、监控、持久化存储等高级特性。在生产者窗口中输入一些文本消息,然后按 Enter 发送。ZooKeeper 会在新窗口中运行。在另一个命令提示符窗口中,同样切换到 Kafka 的。Kafka 服务器将在新窗口中运行。在新的命令提示符窗口中,切换到 Kafka 的。,应显示已安装的 Java 版本信息。_win10安装部署kafka

【愚公系列】2023年12月 WEBGL专题-缓冲区对象_js 缓冲数据 new float32array-程序员宅基地

文章浏览阅读1.4w次。缓冲区对象(Buffer Object)是在OpenGL中用于存储和管理数据的一种机制。缓冲区对象可以存储各种类型的数据,例如顶点、纹理坐标、颜色等。在渲染过程中,缓冲区对象中存储的数据可以被复制到渲染管线的不同阶段中,例如顶点着色器、几何着色器和片段着色器等,以完成渲染操作。相比传统的CPU访问内存,缓冲区对象的数据存储和管理更加高效,能够提高OpenGL应用的性能表现。_js 缓冲数据 new float32array

四、数学建模之图与网络模型_图论与网络优化数学建模-程序员宅基地

文章浏览阅读912次。(1)图(Graph):图是数学和计算机科学中的一个抽象概念,它由一组节点(顶点)和连接这些节点的边组成。图可以是有向的(有方向的,边有箭头表示方向)或无向的(没有方向的,边没有箭头表示方向)。图用于表示各种关系,如社交网络、电路、地图、组织结构等。(2)网络(Network):网络是一个更广泛的概念,可以包括各种不同类型的连接元素,不仅仅是图中的节点和边。网络可以包括节点、边、连接线、路由器、服务器、通信协议等多种组成部分。网络的概念在各个领域都有应用,包括计算机网络、社交网络、电力网络、交通网络等。_图论与网络优化数学建模

随便推点

android 加载布局状态封装_adnroid加载数据转圈封装全屏转圈封装-程序员宅基地

文章浏览阅读1.5k次。我们经常会碰见 正在加载中,加载出错, “暂无商品”等一系列的相似的布局,因为我们有很多请求网络数据的页面,我们不可能每一个页面都写几个“正在加载中”等布局吧,这时候将这些状态的布局封装在一起就很有必要了。我们可以将这些封装为一个自定布局,然后每次操作该自定义类的方法就行了。 首先一般来说,从服务器拉去数据之前都是“正在加载”页面, 加载成功之后“正在加载”页面消失,展示数据;如果加载失败,就展示_adnroid加载数据转圈封装全屏转圈封装

阿里云服务器(Alibaba Cloud Linux 3)安装部署Mysql8-程序员宅基地

文章浏览阅读1.6k次,点赞23次,收藏29次。PS: 如果执行sudo grep 'temporary password' /var/log/mysqld.log 后没有报错,也没有任何结果显示,说明默认密码为空,可以直接进行下一步(后面设置密码时直接填写新密码就行)。3.(可选)当操作系统为Alibaba Cloud Linux 3时,执行如下命令,安装MySQL所需的库文件。下面示例中,将创建新的MySQL账号,用于远程访问MySQL。2.依次运行以下命令,创建远程登录MySQL的账号,并允许远程主机使用该账号访问MySQL。_alibaba cloud linux 3

excel离散度图表怎么算_excel离散数据表格-Excel 离散程度分析图表如何做-程序员宅基地

文章浏览阅读7.8k次。EXCEL中数据如何做离散性分析纠错。离散不是均值抄AVEDEV……=AVEDEV(A1:A100)算出来的是A1:A100的平均数。离散是指各项目间指标袭的离散均值(各数值的波动情况),数值较低表明项目间各指标波动幅百度小,数值高表明波动幅度较大。可以用excel中的离散公式为STDEV.P(即各指标平均离散)算出最终度离散度。excel表格函数求一组离散型数据,例如,几组C25的...用exc..._excel数据分析离散

学生时期学习资源同步-JavaSE理论知识-程序员宅基地

文章浏览阅读406次,点赞7次,收藏8次。i < 5){ //第3行。int count;System.out.println ("危险!System.out.println(”真”);System.out.println(”假”);System.out.print(“姓名:”);System.out.println("无匹配");System.out.println ("安全");

linux 性能测试磁盘状态监测:iostat监控学习,包含/proc/diskstats、/proc/stat简单了解-程序员宅基地

文章浏览阅读3.6k次。背景测试到性能、压力时,经常需要查看磁盘、网络、内存、cpu的性能值这里简单介绍下各个指标的含义一般磁盘比较关注的就是磁盘的iops,读写速度以及%util(看磁盘是否忙碌)CPU一般比较关注,idle 空闲,有时候也查看wait (如果wait特别大往往是io这边已经达到了瓶颈)iostatiostat uses the files below to create ..._/proc/diskstat

glReadPixels读取保存图片全黑_glreadpixels 全黑-程序员宅基地

文章浏览阅读2.4k次。问题:在Android上使用 glReadPixel 读取当前渲染数据,在若干机型(华为P9以及魅族某魅蓝手机)上读取数据失败,glGetError()没有抓到错误,但是获取到的数据有误,如果将获取到的数据保存成为图片,得到的图片为黑色。解决方法:glReadPixels实际上是从缓冲区中读取数据,如果使用了双缓冲区,则默认是从正在显示的缓冲(即前缓冲)中读取,而绘制工作是默认绘制到后缓..._glreadpixels 全黑