在Web服务的例外Web

由网友(年轻不嗨何时嗨)分享简介:我的小组正在开发一种基于服务的(.NET WCF)应用程序,我们正在试图决定如何处理我们的内部服务的例外。我们是否应该抛出异常?返回作为XML序列化异常?只是返回一个错误,code?My group is developing a service-based (.NET WCF) application and we...

我的小组正在开发一种基于服务的(.NET WCF)应用程序,我们正在试图决定如何处理我们的内部服务的例外。我们是否应该抛出异常?返回作为XML序列化异常?只是返回一个错误,code?

My group is developing a service-based (.NET WCF) application and we're trying to decide how to handle exceptions in our internal services. Should we throw exceptions? Return exceptions serialized as XML? Just return an error code?

请记住,用户将不会看到这些例外,它的唯一的应用程序的其他部分。

Keep in mind that the user will never see these exceptions, it's only for other parts of the application.

推荐答案

WCF使用SoapFaults作为无论从服务到客户端,或在客户端向服务发送例外的其天然方式

WCF uses SoapFaults as its native way of transmitting exceptions from either the service to the client, or the client to the service.

您可以使用FaultContract属性在合同接口声明的自定义SOAP错误:

You can declare a custom SOAP fault using the FaultContract attribute in your contract interface:

例如:

[ServiceContract(Namespace="foobar")]
interface IContract
{
    [OperationContract]
    [FaultContract(typeof(CustomFault))]
    void DoSomething();
}


[DataContract(Namespace="Foobar")]
class CustomFault
{
    [DataMember]
    public string error;

    public CustomFault(string err)
    {
        error = err;
    }
}

class myService : IContract
{
    public void DoSomething()
    {
    	throw new FaultException<CustomFault>( new CustomFault("Custom Exception!"));
    }
}
阅读全文

相关推荐

最新文章