嵌套异常作为WCF服务

时间:2016-09-01 11:31:43

标签: c# wcf serviceknowntype nested-exceptions

我有一个c#WCF服务,其接口定义如下:

    [ServiceContract]
    [ServiceKnownType(typeof(Exception))]
    [ServiceKnownType(typeof(ArgumentException))]
    [ServiceKnownType(typeof(ArgumentNullException))]
    public interface IDataExchangeService
    {
        [OperationContract]
        Exception DoSomething(bool someParam);
    }

如您所见,该方法应该返回NULL(当方法执行成功时)或包含任意错误消息的异常。该方法已使用ServiceKnownType属性声明,以避免在将异常实例返回给客户端时出错。仅当返回的异常的类型等于声明的ServiceKnownTypes之一并且InnerException为NULL时,此方法才有效。但是,如果我返回一个异常,例如,有一个ArgumentException作为InnerException,我得到错误,说ArgumentException类型是未知的:

There was an error while trying to serialize parameter http://tempuri.org/:DoSomething. The InnerException message was 'Type 'System.ArgumentNullException' with data contract name 'ArgumentNullException:http://schemas.datacontract.org/2004/07/System' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.'.

我现在有2个问题:

  1. 如何在不必将每种可能的类型声明为ServiceKnownType属性的情况下返回任何类型的异常?
  2. 是否可以使用任意InnerException-types返回嵌套异常?

1 个答案:

答案 0 :(得分:0)

您绝对可以捕获所有异常并将其转换为FaultException。 至少你的代码不会被拆除。另一种方法是在你的服务类中实现IErrorHandler并提供一个错误异常。看看这个IErrorHandler Behavior