The correct way to throw exceptions from WCF

I am trying to send exceptions from WCF in the most universal way. Here is what I have:

[ServiceContract] interface IContract { [OperationContract] void Foo(); } class ContractImplementation: IContract { public void Foo() { try { Bar(); } catch (Exception ex) { throw new FaultException<Exception>(ex, ex.Message); } } } 

The exception that actually comes out of Bar is:

 [Serializable] class MyException : Exception { // serialization constructors } 

The error I see in the server side WCF protocol is:

Type 'MyException' with the contract name 'MyException: http://schemas.datacontract.org/2004/07/MyException ' is not expected. Consider using a DataContractResolver or add types that are not statically unknown to the list of known types — for example, using the KnownTypeAttribute attribute or adding them to the list of known types passed to the DataContractSerializer.

What I have tried so far:

 [ServiceKnownType(typeof(MyException))] [ServiceContract] interface IContract { [FaultContract(typeof(MyException))] [OperationContract] void Foo(); } 

But no luck.

+6
source share
2 answers

First, in MyException, remove the inheritance from Exception and make it public.

Secondly, when you declare your service contract, declare an exception as follows:

 [FaultContractAttribute( typeof(MyException), Action = "", Name = "MyException", Namespace = "YourNamespace")] [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults = true)] [OperationContract] void Foo() 

Finally, you can throw your exception as follows:

 throw new FaultException<MyException> ( new MyException(ex.Message), new FaultReason("Description of your Fault") ); 

Hope this helps.

+2
source

Firstly, apologies, I would rather post this as a comment, rather than as an answer. Like a relative noob, I can't!

This article discusses at a decent level of detail how to relay the exception details back: http://www.codeproject.com/Articles/799258/WCF-Exception-FaultException-FaultContract

Afaik, you cannot actually pass the exception to the client itself, because the exception is not SOAP compliant. Also consider whether passing the entire exception could violate the security of your code.

0
source

Source: https://habr.com/ru/post/990007/


All Articles