0

I'm interested in implementing a proper exception handling for my WCF application. After a quick google ride, I've come across two solutions.

  1. Providing FaultExceptions for the client.
  2. General exception handling using IErrorHandler.

What I didn't found, though, was a practical example that combines the two methods - if this is even considered as good practice.

My thoughts:

Throwing FaultExceptions with own detail types

throw new FaultException<StackOverflowFault>(
    new StackOverflowFault(StackOverflowFaultCode.Rules,
        "This question is not considered as constructive."));

Catching unhandled exceptions with IErrorHandler and log them.

public bool HandleError(Exception ex) {
    try {
        SomeLogger.Error(ex.Message, ex.Source);
        return true;
    } catch (Exception) {
        // Well, there was an exception handling the
        // exception :(
        // -> Drop the exception and throw a new one
        throw new Exception("Unknown exception occured.");
    }
}

...and provide faults based on the exception type

(not everything is for the clients eyes!)

public void ProvideFault(Exception error, MessageVersion version, ref Message fault){
    if(error is FaultException) {
        fault = Message.CreateMessage(version, ((FaultException<StackOverflowFault>)error).Reason)
    } else if(error is SqlException) {
        // What would Jon Skeet do?
    }   
}

My question

Is this considered as okay practice? And: If I'm already throwing FaultException in the application that are suitable for the client - does it makes sense to let them be handled by IErrorHandler (which does it automatically)?

4

1 回答 1

1

最佳实践是实现 IErrorHandler。这是因为:

  1. 您的代码不是唯一潜在的异常来源。您调用的方法(或错误)可能会导致 .NET 异常。如果您没有在某处处理该异常并且没有使用IncludeExceptionDetailInFaults(您不应该在生产环境中使用),这看起来像是服务崩溃。
  2. 关注点分离:服务代码调用的任何业务层都不应引用 WCF ( System.ServiceModel),因此应引发标准 .NET 异常。让业务层不知道其托管如何使其更便携和更可测试。
  3. [ FaultContract] 类型需要在 [ OperationContract] 上指定。在较大的应用程序中,您希望将故障生成集中化……换句话说,知道特定的 IErrorHandler 返回一组特定的故障,以便您可以验证合同故障类型是否正确。抛出合约方法未明确支持的故障类型是一个令人讨厌的运行时错误。

您可以在所有服务方法中复制并粘贴一个 try/catch 块以引发 FaultException,但这是一种可怕的代码气味,并且是 IErrorHandler 作为行为提供给您的确切功能。所以改用 IErrorHandler 。

结合这两种模型是可能的。例如,根据需要让 IErrorHandler 处理 FaultExceptions,但这不是常见的做法。

于 2013-06-12T19:09:40.723 回答