在 WCF 服务中处理异常的最佳方法是什么? [英] What is the best approach to handle exceptions in WCF service?

查看:27
本文介绍了在 WCF 服务中处理异常的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两台或多台远程计算机上部署了一个 WCF 服务,并且客户端使用一个基于桌面的应用程序来访问任何 wcf 服务.

I have a WCF service deployed on two or more remote machines and there is a desktop based application that is used by the client to access any wcf service.

WCF服务连接SQL server 2005读写数据.这是一个内网场景,客户端应该在同一个域中.

The WCF service is connected to SQL server 2005 to read and write data. This is an intranet scenario in which the client should be on same domain.

现在可能会有 wcf 服务抛出异常的场景:

Now there can be scenarios where the wcf service throws exceptions:

  1. 无效网址
  2. WCF 服务已关闭
  3. SQL Server 2005 未运行
  4. 客户端不在同一个域中
  5. 身份验证失败
  6. 授权失败

以及许多其他例外情况.

and many other exceptions.

对于每个异常,我必须根据异常执行一些操作或更新状态栏.例如,如果授权失败,我必须提示用户重新输入他们的凭据.

For every exception I have to perform some action or update a status bar, depending on the exception. For example if authorization fails I have to prompt the user to re-enter their credentials.

请提出处理此问题的最佳设计方法.

Please suggest the best design approach to handle this.

推荐答案

您绝对可以捕获并处理发生在您的服务类上的所有异常,并将它们转换为 FaultException 或 FaultException 异常.

You can definitely catch and handle all exceptions that happen on your service class and turn them into a FaultException or FaultException exception.

这样,您就不会错误"(或破坏)客户端和服务器之间的通信渠道.

That way, you won't "fault" (or tear down) the communications channel between your client and server.

更好的方法是在您的服务类上实现 IErrorHandler 接口,该接口提供了一种方法来全局捕获所有发生的异常并提供一个 FaultException,这是符合 SOAP 的.

Even better approach would be to implement the IErrorHandler interface on your service class that provides a way to globally catch all exceptions as they happen and provide a FaultException instead, that's SOAP compliant.

您甚至可以将 IErrorHandler 变成可在配置中打开或关闭的可配置行为.

You can even turn your IErrorHandler into a configurable behavior that can be turned on or off in config.

有关详细信息,请参阅这些文章和博文:

See these articles and blog posts for more details:

这篇关于在 WCF 服务中处理异常的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆