When using the WCF service, you should use FaulException because this is Soap's native approach for handling errors (the exception is not serializable either).
In a typical scenario, you first add the typed FaultContract for each operating contract.
// NOTE: This is the std wcf template [ServiceContract] public interface IService1 { [FaultContract(typeof(int))] [FaultContract(typeof(string))] [FaultContract(typeof(DateTime))] [OperationContract] string GetData(int value); }
You will send a dialed error exception for all cases of failures in which you decide that the client needs information about the malfunction.
Your client may catch a FaultException type, which is a custom SOAP error specified in the operation contract.
ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client(); try { Console.WriteLine("Returned: {0}", proxy.GetData(-5)); } catch (FaultException<int> faultOfInt) { //TODO proxy.Abort(); } catch (FaultException<string> faultOfString) { //TODO proxy.Abort(); } catch (FaultException<DateTime> faultOfDateTime) { //TODO proxy.Abort(); } catch (FaultException faultEx) { Console.WriteLine("An unknown exception was received. " + faultEx.Message + faultEx.StackTrace ); proxy.Abort(); } catch (Exception e) { //generic method Type exceptionType = e.GetType(); if (exceptionType.IsGenericType && exceptionType.GetGenericTypeDefinition() == typeof(FaultException<>)) { PropertyInfo prop = exceptionType.GetProperty("Detail"); object propValue = prop.GetValue(e, null); Console.WriteLine("Detail: {0}", propValue); } else { Console.WriteLine("{0}: {1}", exceptionType, e.Message); } }
In the end, since a FaultException inherits Exception, you can still use reflection to get the internal type and details of the failure, as shown here.
Also note that common expected exceptions to communication methods in the WCF client include TimeoutException, CommunicationException, and any derived CommunicationException class (for example, FaultException). They indicate a problem during communication that can be safely handled by interrupting the WCF client and reporting a communication error.
source share