Capturing WCF Exception Exception

A single-level application can distinguish exceptions:

Exception ex; if (ex is System.DirectoryServices.AccountManagement.PasswordException) ... 

where ex is just a general exception.

When you go to WCF for a tiered level, you lose all this and you need to use the FaultException mechanism.

The problem is that I cannot find a way to do this.

In my client, I want to catch FaultException types and then distinguish between them, for example:

 catch (FaultException ex) { if FaultException is (PasswordExceptionFault) ... etc } 

Is there any way to do this?

Otherwise, I should have many catch constructions - one for each type of Fault exception.

+4
source share
2 answers

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.

+8
source

Just use something like:

 if (error is FaultException<ServerTooBusyException>) { // Do something } 
-2
source

All Articles