I have a question regarding WCF fault exceptions. I am implementing the IErrorHandler interface and creating a FaultException
.
My question is this: When am I creating a FaultException
, is there a pattern that I must follow to send a friendly error message to the client?
I log the actual exception using the HandleError
method to the database and creating a FaultException
in the ProvideFault
method.
Given delow, there is my sample implementation of IErrorHandler interface.
public bool HandleError(Exception error)
{
System.Diagnostics.Debug.WriteLine(error.Message);
// Log the error to the Db
return true;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
// Here is a sample that I was playing with.
MessageFault faultException;
if(error is DataException)
faultException = new FaultException<string>(ErrorStrings.DatabaseOpenError, new FaultReason(ErrorStrings.DatabaseOpenError)).CreateMessageFault();
else if (error is NullReferenceException)
faultException = new FaultException<string>(ErrorStrings.NullDataError, new FaultReason(ErrorStrings.NullDataError)).CreateMessageFault();
else
faultException = new FaultException<string>(ErrorStrings.GeneralError, new FaultReason(ErrorStrings.GeneralError)).CreateMessageFault();
fault = Message.CreateMessage(version, faultException, "");
}
I need some clarity on what exactly has to be done inside ProvideFault
method to return a friendly Fault to the user. I am also planning to use localization to display errors. Not sure if this will be done by the client or if service should send localized messages.
Based on what I read, I should not send information of the stack from the error or EntityFramework errors, like EntityValidation errors and so on, to the client due to security reasons.
In this case, will I need to check for the type of exception and mine the details to be more appropriate before sending to the client?
The main requirement is to use the FaultContractAttribute so WCF understands the service contract being fulfilled. Please see http://msdn.microsoft.com/en-us/library/ms752208(v=vs.110).aspx
WCF will then also make sure your WSDL reflects your fault contracts.