问题描述
我有一个可能引发异常的服务。我希望能够在客户端捕获异常。我感兴趣的主要异常是 DbUpdateException
和 InvalidOperationException
。对于其余的异常,只需知道已引发异常即可。
I have a service that may throw exceptions. I want to be able to catch the exceptions at the client. The main Exceptions I am interested in are DbUpdateException
and InvalidOperationException
. For the rest of the exceptions it is enough to know that an exception has been throws.
如何在客户端捕获异常?
How can I have exceptions caught in the client?
推荐答案
如果您的WCF服务引发异常,则默认情况下它将作为 FaultException
出现在客户端。您可以将服务配置为在故障中包括异常详细信息,例如:
If your WCF service throws an exception, then by default it will come to the client as a FaultException
. You can configure your service to include exception details in faults, like so:
<serviceDebug includeExceptionDetailInFaults="true" />
但是您可能不想这样做,将内部实现细节公开给客户的好主意。
But you probably don't want to do this, it's never a good idea to expose internal implementation details to clients.
如果要区分不同的服务错误,可以创建自己的类,并将其注册为您的错误。服务会抛出。您可以在服务合同级别执行此操作:
If you want to distinguish between different service faults, you can create your own class, and register this as a fault that your service will throw. You can do this at the service contract level:
public interface YourServiceContract
{
[FaultContract(typeof(YourFaultClass))]
[OperationContract(...)]
YourServiceResponseClass YourServiceOperation(YourServiceRequestClass request);
}
用于故障合同的类不必执行任何操作(就像您对自定义 Exception
所做的那样),它只会被包装在通用的 FaultContract
对象中。然后,您可以在客户端代码中捕获以下内容:
The class you use for your fault contract doesn't have to implement anything (as you would have to do for a custom Exception
), it will just get wrapped in a generic FaultContract
object. You can then catch this in the client code like this:
try
{
// service operation
}
catch (FaultException<YourFaultClass> customFault)
{
...
}
catch (FaultException generalFault)
{
...
}
这篇关于WCF将异常传递给客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!