WCF: Error Handling and FaultExceptions

What If There's No Error Handling?

 
Suppose I write a WCF web service with no try-catch blocks and no error handling. What happens when my web service throws an exception? Since I don't have any error handling, WCF catches the exception for me. It sends the client (the program that called my web service) a FaultException with the following message:
 
"The server was unable to process the request due to an internal error."
 
Whenever there's an unhandled exception, that's all the information the client gets. WCF doesn't send the client the exception message or the stack trace or any of the other information that was contained in the exception.
 
There are a number of reasons why WCF does this. One reason is that the Exception class is specific to .Net. WCF was designed to make web services that can be called by anyone, including clients that are not written in .Net. The client program can be written in Java or PHP or a variety of other languages. So WCF doesn't assume that the clients were written in .Net, and it doesn't send them .Net specific responses.
 
Another reason WCF doesn't send the client more information is that this might not be safe. It's not safe to provide the stack trace to anyone that may call. Detailed error messages are also risky. For example, it's not safe to inform the caller that the database insert failed because user name "andrew.fenster" is already in use. The safer practice is to write this information to an error log and provide much less detailed error information to the caller.
 

Providing More Information With FaultExceptions

 
A bare FaultException may be safe, but it doesn't provide enough information. I may not want to pass the full stack trace, but I want to provide at least basic information about what went wrong. WCF provides multiple ways to do this.
 
The FaultException class itself includes several ways to provide more information. The FaultException class includes these constructors (among others):
  1. public FaultException(string reason);  
  2. public FaultException(string reason, FaultCode code);  
  3. public FaultException(FaultReason reason);  
  4. public FaultException(FaultReason reason, FaultCode code);  
The simplest way to provide information is the first of these:
  1. try  
  2. {  
  3.     // do something  
  4. }  
  5. catch (Exception ex)  
  6. {  
  7.      myLogger.LogException(ex);  
  8.      throw new FaultException("Your request timed out. Please try again later.");  
  9. }  
The client can capture the FaultException and read the message as follows:
  1. try  
  2. {  
  3.      // call the web service  
  4. }  
  5. catch (FaultException ex)  
  6. {  
  7.      Console.WriteLine(ex.Message);  
  8. }  
As you can see from the FaultException constructors, you can create a FaultException with a string, a FaultCode, a FaultReason or some combination of these.
 
The FaultReason class lets you provide the same error message in multiple languages. If you look at the list of FaultException constructors, you will see that you can either provide an error message in a string or a collection of error messages in a FaultReason. You don't need both.
 
A FaultCode allows you to provide a code (a string) to tell the client what went wrong. For example:
  1. try  
  2. {  
  3.       // do something  
  4. }  
  5. catch (Exception ex)  
  6. {  
  7.      myLogger.LogException(ex);  
  8.      FaultCode code = new FaultCode("Invalid Operation");  
  9.      throw new FaultException("Customer name cannot be null.", code);  
  10. }  
The client can catch the FaultException and read the FaultCode as follows:
  1. try  
  2. {  
  3.      // call the web service  
  4. }  
  5. catch (FaultException ex)  
  6. {  
  7.      Console.WriteLine("FaultCode: " + ex.Code);  
  8.      Console.WriteLine("Message: " + ex.Message);  
  9. }  

The FaultException<T> class

 
The FaultException class gives you several ways to inform the client about what went wrong. Sometimes, however, you may want more.
 
The FaultException<T> class is derived from the FaultException class. As with the FaultException class, you can pass in some combination of string, FaultCode and FaultReason. You can also pass in some additional value T. T can be a value or an entire class object. For example, you could define your own error class:
  1. [DataContract]  
  2. public class ErrorMessage  
  3. {  
  4.       private Guid ticketNumber;  
  5.        [DataMember]  
  6.       public Guid TicketNumber  
  7.       {  
  8.            get { return ticketNumber; }  
  9.            set { ticketNumber = value; }  
  10.       }  
  11.   
  12.       [DataMember]  
  13.       public string Message  
  14.       {  
  15.            get { return "An error has occurred. For more information,   
  16.                              call us and tell us your ticket number."; }  
  17.       }      public ErrorMessage(Guid newTicket)  
  18.       {  
  19.            ticketNumber = newTicket;  
  20.       }  
  21. }  
You could use this as follows:
  1. try  
  2. {  
  3.       // Do something  
  4. }  
  5. catch (Exception ex)  
  6. {  
  7.       Guid ticket = myLogger.LogException(ex);         
  8.       ErrorMessage message = new ErrorMessage(ticket);  
  9.       throw new FaultException<ErrorMessage>(message);  
  10. }  
The client can catch this FaultException as follows:
  1. try  
  2. {  
  3.       // call the web service  
  4. }  
  5. catch (FaultException<ErrorMessage> ex)  
  6. {  
  7.       Guid ticket = ex.Detail.TicketNumber;  
  8.       string message = ex.Detail.Message;  
  9. }  
Of course you could also throw in a FaultCode or a FaultReason, since FaultException<T> is derived from FaultException. FaultException<T> includes these constructors:
  1. public FaultException(T detail);  
  2. public FaultException(T detail, string reason);  
  3. public FaultException(T detail, FaultReason reason);  
  4. public FaultException(T detail, string reason, FaultCode code);  
  5. public FaultException(T detail, FaultReason reason, FaultCode code);  
When you use the FaultException<T> class, T can be any type, provided in can be serialized. If you are going to use your own custom class, you should define a DataContract for your class, as shown above.
 

FaultContracts

 
If you are going to use the FaultException<T> class, you need to create a FaultContract. The FaultContract tells the client program what type of Faults each method can throw. For example:
  1. [ServiceContract]  
  2. interface IMyService  
  3. {  
  4.     [OperationContract]  
  5.     [FaultContract(typeof(ErrorMessage))]  
  6.     int DoSomething();  
  7. }  
This FaultContract informs the client that when it calls DoSomething( ) it may receive a fault of type FaultException<ErrorMessage>.
 
You can specify more than one fault type. For example:
  1. [ServiceContract]  
  2. interface IMyService  
  3. {  
  4.      [OperationContract]  
  5.      [FaultContract(typeof(ErrorMessage))]  
  6.      [FaultContract(typeof(Guid))]  
  7.      int DoSomething();  
  8. }  
Now my method can throw either FaultException<ErrorMessage> or FaultException<Guid>.
 
If a web service throws a FaultExeption<T> of a type not declared in the ServiceContract, it will not reach the client. For example, if the ServiceContract says I will throw a FaultException<ErrorMessage>, and my service instead throws a FaultException<string>, WCF will block my fault. Instead, it will send the client a bare FaultException with the generic message "The server was unable to process the request due to an internal error."
 
Best Practices
 
There are no shortage of people offering their own advice about error handling. I have only a few points to make.
 
First and most important, you should be very cautious about providing detailed information to the client about what went wrong. Most error details are either a security risk or simply irrelevant to the client. For example, the Stack Trace contains details about your code which should not be revealed. Even if the client is another division within your own company, they don't need you to send them the Stack Trace. If you sent them the Stack Trace, what would they do with it? Likewise, it's not a good idea to simply catch exceptions and pass the exception Message to the client.
 
There are only a few types of messages that the client may care about. For example, if the client did not provide a required field, informing the client might be useful. If the system is down temporarily, you could tell the client to try later. Error messages that reveal details about your code, however, don't help the client but do provide security risks.
 
Using an ErrorMessage class like the one shown above may be sufficient. The client is informed that something went wrong. It anyone needs more information, they can provide you with a ticket number, and you can look up the error in the error log.
 
One other suggestion: if you are going to provide any significant error information, it would be best to have a FaultContract. Even though the basic FaultException class allows you to pass a message and a FaultCode and a FaultReason (and a few other things not discussed in this article), it makes sense to forego these and use a FaultException<T>, with all your error information inside the detail object T. That way the client knows exactly what to expect and doesn't try reading a value from the FaultReason when there's no FaultReason provided.
 
In conclusion, WCF provides you with a lot of options for error handling. As long as you think carefully about what information you are providing and the format in which you provide it, you should come out fine.


Similar Articles