gpt4 book ai didi

c# - 使用 IErrorHandler 的 WCF 异常处理

转载 作者:太空狗 更新时间:2023-10-29 19:55:57 24 4
gpt4 key购买 nike

我基本上是在实现 IErrorHandler 接口(interface)来捕获来自 WCF 服务的各种异常,并通过实现 ProvideFault 方法将其发送到客户端。

然而,我面临一个关键问题。所有异常都作为 FaultException 发送给客户端,但这会使客户端无法处理他可能已在服务中定义的特定异常。

考虑:在 OperationContract 实现之一中定义并抛出的 SomeException。抛出异常时,使用以下代码将其转换为故障:

var faultException = new FaultException(error.Message);
MessageFault messageFault = faultException.CreateMessageFault();
fault = Message.CreateMessage(version, messageFault, faultException.Action);

这确实将错误作为字符串发送,但客户端必须捕获一般异常,例如:

try{...}
catch(Exception e){...}

而不是:

try{...}
catch(SomeException e){...}

不仅像SomeException这样的自定义异常,像InvalidOperationException这样的系统异常也不能用上面的流程捕获。

关于如何实现此行为有什么想法吗?

最佳答案

在 WCF 中,希望使用描述为契约的特殊异常,因为您的客户端可能不是具有有关标准 .NET 异常信息的 .NET 应用程序。为此,您可以在服务中定义 FaultContract,然后使用 FaultException类。

服务器端

[ServiceContract]
public interface ISampleService
{
[OperationContract]
[FaultContractAttribute(typeof(MyFaultMessage))]
string SampleMethod(string msg);
}

[DataContract]
public class MyFaultMessage
{
public MyFaultMessage(string message)
{
Message = message;
}

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

class SampleService : ISampleService
{
public string SampleMethod(string msg)
{
throw new FaultException<MyFaultMessage>(new MyFaultMessage("An error occurred."));
}
}

此外,您可以在配置文件中指定服务器在其 FaultExceptions 中返回异常详细信息,但在生产应用中不建议这样做:

<serviceBehaviors>
<behavior>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>

之后,您可以重写处理异常的方法:

var faultException = error as FaultException;
if (faultException == null)
{
//If includeExceptionDetailInFaults = true, the fault exception with details will created by WCF.
return;
}
MessageFault messageFault = faultException.CreateMessageFault();
fault = Message.CreateMessage(version, messageFault, faultException.Action);

客户:

try
{
_client.SampleMethod();
}
catch (FaultException<MyFaultMessage> e)
{
//Handle
}
catch (FaultException<ExceptionDetail> exception)
{
//Getting original exception detail if includeExceptionDetailInFaults = true
ExceptionDetail exceptionDetail = exception.Detail;
}

关于c# - 使用 IErrorHandler 的 WCF 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17961564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com