WCF - 异常处理



WCF 服务开发人员可能会遇到一些无法预见的错误,需要以合适的方式向客户端报告。这些错误,称为异常,通常使用 try/catch 块处理,但这又非常依赖于具体的技术。

由于客户端关注的并非错误是如何发生的或导致错误的因素,因此 WCF 使用 SOAP 错误契约来将错误消息从服务传达给客户端。

错误契约使客户端能够以文档化的方式查看服务中发生的错误。以下示例可以更好地理解这一点。

步骤 1 - 创建一个简单的计算器服务,其中包含除法运算,该运算将生成一般异常。

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Runtime.Serialization;
usingSystem.ServiceModel;
usingSystem.Text;

namespace Calculator {
   // NOTE: You can use the "Rename" command on the "Refactor" menu to change 
   // the interface name "IService1" in both code and config file together.
   
   [ServiceContract]
   
   public interface IService1 {
      [OperationContract]
      int divide(int num1, int num2);
      // TODO: Add your service operations here
   }
}

类文件的代码如下所示:

Wcf Exception Handling 2

现在,当我们尝试将数字 10 除以零时,计算器服务将抛出一个异常。

Wcf Exception Handling 3

Wcf Exception Handling 4

可以使用 try/catch 块处理异常。

Wcf Exception Handling 5

现在,当我们尝试将任何整数除以 0 时,它将返回 10,因为我们在 catch 块中处理了它。

Wcf Exception Handling 6

步骤 2 - 在此步骤中,使用 FaultException 将异常信息从服务传达给客户端。

public int Divide(int num1, int num2) { 
   //Do something 
   throw new FaultException("Error while dividing number"); 
}
Wcf Exception Handling 7

步骤 3 - 也可以创建自定义类型来使用 FaultContract 发送错误消息。创建自定义类型的必要步骤如下所述:

通过使用数据契约定义类型,并指定要返回的字段。

服务操作由 FaultContract 属性装饰。还指定了类型名称。

创建一个服务实例以引发异常,并为自定义异常属性赋值。

广告

© . All rights reserved.