gpt4 book ai didi

没有异常消息详细信息的 WCF CommunicationException

转载 作者:行者123 更新时间:2023-12-04 19:16:35 26 4
gpt4 key购买 nike

我从不了解 WCF 的一件事是,当服务器遇到未处理的异常时,为什么没有异常消息详细信息传播回调用客户端。

例如,如果我有以下服务器代码

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class Server : IServer
{
public DTO GetDTO()
{
DTO dto = new DTO();
dto.dto = dto;
return dto;
}

}

public class DTO
{
public DTO dto;
}

[ServiceContract]
public interface IServer
{
[OperationContract]
DTO GetDTO();
}

我特意引入了一个ObjectGraph,在返回DTO对象时引发序列化异常。

如果我有一个客户端调用此服务器的 GetDTO()方法,我会得到以下 CommunicationException .

The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:58.9350000'.



这是绝对没用的。它没有内部异常,甚至没有真正的异常消息。

如果您随后使用 Microsoft Service TraceViewer,您将看到异常,但您必须为此打开诊断跟踪。

应该返回的异常消息是

There was an error while trying to serialize parameter http://tempuri.org/:GetDTOResult. The InnerException message was 'Object graph for type 'TestWCFLib.DTO' contains cycles and cannot be serialized if reference tracking is disabled.'. Please see InnerException for more details.



那么有人能告诉我如何在客户端显示正确的异常消息吗?显然,设置 IncludeExceptionDetailInFaults为 true 没有任何区别。

最佳答案

我认为服务器错误不会传播到客户端是设计使然。这通常是一种不向客户端公开服务器内部结构的做法,因为客户端服务器架构的主要目的是服务器的独立性。

您仍然可以通过使用 Fault Exception 来实现这一点。

用故障契约(Contract)装饰您的服务声明

[ServiceContract]
public interface IServer
{
[OperationContract]
[FaultContract(typeof(MyApplicationFault))]
DTO GetDTO();
}

然后在 servcie 实现中捕获错误并抛出错误异常。
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class Server : IServer
{
public DTO GetDTO()
{
try
{
DTO dto = new DTO();
dto.dto = dto;
return dto;
}
catch (Exception ex)
{
MyApplicationFault fault = new MyApplicationFault(...);
throw new FaultException<MyApplicationFault>(fault);
}
}

}

并在客户端捕获异常
IServer proxy = ...;    //Get proxy from somewhere
try
{
proxy.GetDTO();
}
catch (TimeoutException) { ... }
catch (FaultException<MyApplicationFault> myFault) {
MyApplicationFault detail = myFault.Detail;
//Do something with the actual fault
}
catch (FaultException otherFault) { ... }
catch (CommunicationException) { ... }

希望这可以帮助。
对于一个不错的教程,请参阅 Code Project Tutorial on Fault Exception

关于没有异常消息详细信息的 WCF CommunicationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7404478/

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