WCF:故障契约和异常层次结构
我的系统由两个站点组成,它们之间使用 WCF 进行通信。有时,当一个站点在其对等站点上调用操作时,会引发异常,我正在尝试确定在这种情况下使用 WCF 的故障契约的最佳方法是什么。
在过去的项目中,我习惯于创建一个不平凡的异常层次结构,例如:
BaseSystemException
CustomerServiceException
CustomerNotFoundException
BadCustomerNameException
CustomerAlreadyExistsException
...
OrderServiceException
OrderNotFoundException
OrderAlreadyExistsException
...
但是,在 WCF 中实现这样的层次结构很快就会变得令人厌烦,因为我必须在其自己的故障契约中指定每个具体的异常类型。现在,由于这两个服务都是同一系统的一部分,因此不存在泄漏信息/敏感调用堆栈等问题。我希望 B 在其异常中提供尽可能多的信息,以便 A 能够做出相应的反应。我应该注意到,在实践中,许多异常都是以相同的方式处理的(操作失败并通知用户),但是在设计我的异常方案时,我不想假设对所有异常进行相同的处理。
任何人都可以建议一种不需要为每种异常类型提供故障契约的方法吗?有更简单的方法吗?毕竟这是一个内部接口。我想要使用异常层次结构是否过于理想化?
My system consists of two sites, communicating between themselves using WCF. Occasionally, exceptions are thrown when one site invokes operations on its peer, and I'm trying to decide what's the best way to use WCF's FaultContracts in such cases.
In past projects, I was used to creating a non-trivial exception hierarchy, e.g.:
BaseSystemException
CustomerServiceException
CustomerNotFoundException
BadCustomerNameException
CustomerAlreadyExistsException
...
OrderServiceException
OrderNotFoundException
OrderAlreadyExistsException
...
However, implementing such a hierarchy quickly becomes tiresome in WCF because I have to specify each concrete exception type in its own FaultContract. Now, since both services are part of the same system, there is no issue of leaking information/sensitive callstacks/etc. I want B to provide as much information as possible in its exceptions, so that A can react accordingly. I should note that in practice, many of these exceptions are dealt with in the same way (failing the operation and notifying the user), but when designing my exception scheme, I don't want to assume identical handling for all exceptions.
Can anyone suggest an approach that doesn't require a FaultContract for each exception type? Is there an easier way? This is an internal interface, after all. Am I being too idealistic in wanting to use an exception hierarchy?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否考虑过抛出 FaultException ?这不会破坏您的 WCF 服务,因此您的客户端可以处理异常。
编辑:
由于您想保留异常类型,我认为没有办法摆脱使用FaultContracts。我唯一能建议的是巩固你的一些例外情况。
例如,
CustomerNotFoundException
和BadCustomerNameException
可能会变成FailedToFetchCustomerException
,然后消息可以传达原因。Have you looked into throwing a FaultException instead? This doesn't break your WCF service so your client can handle the exception.
EDIT:
As you want to keep the type of exception I don't think there is a way out of using FaultContracts. The only thing I can suggest is to consolidate some of your exceptions.
e.g
CustomerNotFoundException
andBadCustomerNameException
could becomeFailedToFetchCustomerException
and then the message can convey the reason why.