且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WCF将异常传递给客户端

更新时间:2022-06-18 22:10:54

如果您的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)
{
   ...
}