In the previous example I enabled includeExceptionDetailInFaults in app.config to get some more details on exceptions thrown over the wire. While this is nice for developing once the service hits production this can breach security. This is why it is set to false by default. There are, however, many times that you want to inform the client of an error. You can do this explicitly by throwing a FaultException. The EchoService Echo operation would look something like this:
public EchoMessage Echo(EchoMessage message) { if (message.Text == "Fault") throw new FaultException("FaultException thrown!"); message.Invoked = DateTime.Now; message.Text = String.Concat( Enumerable.Repeat(message.Text, 3)); _echoList.Add(message); return message; }
On the client side the FaultException is rethrown so we are able to catch and handle it.
using System; using System.ServiceModel; using EchoClientConsole.EchoServiceReference; namespace EchoClientConsole { internal class Program { private static void Main() { var channel = new EchoServiceClient( "WSHttpBinding_IEchoService" ); try { channel.Echo(new EchoMessage { Created = DateTime.Now, Text = "Fault" }); Console.ReadLine(); channel.Close(); } catch (FaultException exception) { Console.WriteLine(exception.Message); Console.ReadLine(); channel.Abort(); } } } }
