WCF故障合同的企业库异常处理 - 客户端

时间:2010-05-13 14:59:47

标签: wcf exception logging enterprise-library fault

我有一个与WCF服务通信的Windows服务。 WCF服务都是故障屏蔽并生成自定义UserFaultContracts和ServiceFaultContracts。没问题。

在Windows服务中,我使用EntLib进行异常处理和日志记录。

我不想尝试捕获错误

try
{
}
catch (FaultException<UserFaultContract>)
{
}

我想使用EntLib

try
{
}
catch (Exception ex)
{
var rethrow = ExceptionPolicy.HandleException(ex, "Transaction Policy");
if (rethrow) throw;
}

但是,这也适用于我的Tranasaction Policy我想记录UserFaultContract的详细信息。这是我脱胶的地方。而且我讨厌变得脱毛。捕获并记录故障......但我无法获得故障的详细信息。

我的例外政策是

  <add name="Transaction Policy">
    <exceptionTypes>
      <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        postHandlingAction="None" name="Exception">
        <exceptionHandlers>
          <add logCategory="General" eventId="200" severity="Error" title="Transaction Error"
            formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            priority="2" useDefaultLogger="true" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            name="Logging Handler" />
        </exceptionHandlers>
      </add>
      <add type="System.ServiceModel.FaultException, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        postHandlingAction="None" name="FaultException">
        <exceptionHandlers>
          <add logCategory="General" eventId="200" severity="Error" title="Service Fault"
            formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            priority="2" useDefaultLogger="true" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            name="Logging Handler" />
        </exceptionHandlers>
      </add>
    </exceptionTypes>
  </add>

记录的异常是:

时间戳:2010年5月13日14:53:40 消息:HandlingInstanceID:e9038634-e16e-4d87-ab1e-92379431838b

类型'System.ServiceModel.FaultException`1 [[LCI.DispatchMaster.FaultContracts.ServiceFaultContract,LCI.DispatchMaster.FaultContracts,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]'的例外情况发生了捕获。

05/13/2010 10:53:40 键入:System.ServiceModel.FaultException`1 [[LCI.DispatchMaster.FaultContracts.ServiceFaultContract,LCI.DispatchMaster.FaultContracts,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]],System.ServiceModel,Version = 3.0.0.0 ,Culture = neutral,PublicKeyToken = b77a5c561934e089 消息:DispatchMaster服务存在内部故障。 资料来源:mscorlib 帮助链接: 详细信息:LCI.DispatchMaster.FaultContracts.ServiceFaultContract 行动:http://LCI.DispatchMaster.LogicalChoices.com/ITruckMasterService/MergeScenarioServiceFaultContractFault 代码:System.ServiceModel.FaultCode 原因:DispatchMaster服务存在内部故障。 数据:System.Collections.ListDictionaryInternal TargetSite:Void HandleReturnMessage(System.Runtime.Remoting.Messaging.IMessage,System.Runtime.Remoting.Messaging.IMessage) 堆栈跟踪:

在故障联系中有一个ID和一条消息。正如您所看到的,我会像EntLib要记录的ID和消息一样。

我假设我将不得不编写一个自定义处理程序来解决故障细节 - 但我想我会问我是否遗漏了EntLib中的某些东西,这可能会帮助我避免这个任务。

感谢愿意提供帮助的任何人。

2 个答案:

答案 0 :(得分:0)

我现在正在进行非常类似的研究,如何正确处理WCF故障和EAB。我认为this article可能对你非常有用。我没有尝试过,但看起来并不太沉闷。

答案 1 :(得分:0)

如果您确定在WCF服务中正确配置了所有内容,那么您应该能够获得在服务端填充的消息。

以下代码应在客户端显示完整的异常详细信息。

private void CalculateDivision(decimal numerator, decimal denominator)
{
    try
    {
        // Create an instance of service client.
        ICalculatorService svc = new CalculatorServiceClient();
        // Call service method.
        Console.WriteLine("Result is: {0}", svc.Divide(numerator, denominator));
    }
    catch (Exception ex)
    {
        // Show details of the exception returned to the calling code.  
        ShowExceptionDetails(ex);
        // Show details of the fault contract returned from the WCF service.  
        ShowFaultContract(ex);
    }
}


public void ShowExceptionDetails(Exception ex)
{
    Console.WriteLine("Exception type {0} was thrown.", ex.GetType().ToString());
    Console.WriteLine("Message: '{0}'", ex.Message);
    Console.WriteLine("Source: '{0}'", ex.Source);
    if (null == ex.InnerException)
    {
        Console.WriteLine("No Inner Exception");
    }
    else
    {
        Console.WriteLine();
        Console.WriteLine("Inner Exception: {0}", ex.InnerException.ToString());
    }
    Console.WriteLine();
}

private static void ShowFaultContract(Exception ex)
{
    var faultContract = ex as FaultException<CalculatorFault>;
    if (faultContract != null)
    {
        CalculatorFault calculatorFault = faultContract.Detail;
        Console.WriteLine("Fault contract detail: ");
        Console.WriteLine("Fault ID: {0}", calculatorFault.FaultID);
        Console.WriteLine("Message: {0}", calculatorFault.FaultMessage);
    }
}

如果它仍然不起作用,那么服务方面确实存在问题。让我们看看上面定义的特定客户端的服务代码应该是什么样的。

[ServiceContract]
public interface ICalculatorService
{
    [OperationContract]
    [FaultContract(typeof(CalculatorFault))]
    decimal Divide(decimal num1, decimal num2);
}

[DataContract]
public class CalculatorFault
{
    [DataMember]
    public Guid FaultID { get; set; }

    [DataMember]
    public string FaultMessage { get; set; }
}

[ExceptionShielding("CalculatorServicePolicy")]
public class CalculatorService : ICalculatorService
{
    public decimal Divide(decimal num1, decimal num2)
    {
      Calculator calc = new Calculator();
      return calc.Divide(num1, num2);
    }
}

//Call the following function in Application_Start function of your Global.asax file
private void ConfigureExceptionHandlingBlock()
{
    var policies = new List<ExceptionPolicyDefinition>();

    var mappings = new NameValueCollection();
    mappings.Add("FaultID", "{Guid}");
    mappings.Add("FaultMessage", "{Message}");

    var calculatorServicePolicy = new List<ExceptionPolicyEntry>
        {
            new ExceptionPolicyEntry(typeof(Exception),
                PostHandlingAction.ThrowNewException,
                new IExceptionHandler[]
                {
                    new FaultContractExceptionHandler(typeof(CalculatorFault), "Some internal service Error. Check service logs.", mappings)
                })
        };
    policies.Add(new ExceptionPolicyDefinition("CalculatorServicePolicy", calculatorServicePolicy));
    ExceptionManager exManager = new ExceptionManager(policies);
    ExceptionPolicy.SetExceptionManager(exManager);
}