wcf Handling exceptions Throwing a user-friendly message with FaultException


Example

You can handle exceptions and throw a most friendly message like 'Unavailable service' throwing a FaultException:

try
{
    // your service logic here
}
catch (Exception ex)
{
    // You can do something here, like log the original exception
    throw new FaultException("There was a problem processing your request");
}

In your client, you can easily get the message:

try
{
    // call the service
}
catch (FaultException faultEx)
{
   var errorMessage = faultEx.Message;
   // do something with error message
}

You can distinguish the handled exception from other exceptions, like a network error, adding other catches to your code:

try
{
    // call the service
}
catch (FaultException faultEx)
{
   var errorMessage = faultEx.Message;
   // do something with error message
}
catch (CommunicationException commProblem)
{
    // Handle the communication error, like trying another endpoint service or logging
}