I have a lot of legacy code that is now a backend for a WCF REST service - it used to be a usual WCF service backend before, if that matters. I want to implement a mechanism tha
When you change the WCF SOAP services to REST, the whole mindset of error reporting and handling changes.
In SOAP, faults are part of your contract. In REST, they simply become codes that you output in the HTTP response code and description.
Here is a catch snippet:
catch (Exception e)
{
Trace.WriteLine(e.ToString());
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.UnsupportedMediaType; // or anything you want
response.StatusDescription = e.Message;
return null; // I was returning a class
}
So I would suggest you create a helper code which creates relevant error codes for you and put in the response.
This what I did in the past
public class MyServerBehavior : IServiceBehavior {
public void AddBindingParameters(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase,
Collection<ServiceEndpoint> endpoints,
BindingParameterCollection bindingParameters) {
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase) {
foreach (ChannelDispatcher chDisp in serviceHostBase.ChannelDispatchers) {
chDisp.IncludeExceptionDetailInFaults = true;
if (chDisp.ErrorHandlers.Count > 0) {
// Remove the System.ServiceModel.Web errorHandler
chDisp.ErrorHandlers.Remove(chDisp.ErrorHandlers[0]);
}
// Add new custom error handler
chDisp.ErrorHandlers.Add(new MyErrorHandler());
}
}
public void Validate(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase) {
}
}
MyErrorHandler was my class that implemented IErrorHandler.