I have a c# WCF service with the following interface definition:
[ServiceContract]
[ServiceKnownType(typeof(Exception))]
[ServiceKnownType(typeof(ArgumentException))]
[ServiceKnownType(typeof(ArgumentNullException))]
public interface IDataExchangeService
{
[OperationContract]
Exception DoSomething(bool someParam);
}
As you can see, the method is supposed to either return NULL (when the execution of the method was successful) or an exception containing an arbitrary error message. The method is already declarated with the ServiceKnownType-attributes to avoid errors when returning an exception instance to the client. This works only if the type of the returned exception is equal to one of the declared ServiceKnownTypes and if the InnerException is NULL. However, if I return an exception thats has, for example, an ArgumentException as InnerException, I get the error saying that the ArgumentException type is unknown:
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.'.
I have 2 questions now:
- How can I make it so that any type of exception can be returned without having to declare each possible type as ServiceKnownType attribute?
- Is it possible to return nested exceptions with arbitrary InnerException-types?
You can definitely catch all the exceptions and turn them into a FaultException. Atleast your code wont tear down .Another method would be to implement IErrorHandler in your service class and provide a fault exception.Take a look at this IErrorHandler Behavior