Hopefully there are some WCF wizards out there that can spot my mistake here.
I am trying to set up a global error handler via an IErrorHandler based behaviorExtension on a RESTful JSON WCF Service. The method is decorated as such:
[OperationContract]
[WebGet(UriTemplate = "screens/info", ResponseFormat = WebMessageFormat.Json)]
The IErrorHandler implementation is:
public class ErrorHandler : IErrorHandler
{
public void ProvideFault(Exception error,
MessageVersion version,
ref Message fault)
{
var error = new JsonError
{
Message = error.Message,
FaultCode = -1,
StackTrace = error.StackTrace
};
fault = Message.CreateMessage(version,
"",
ideaScreeningError,
new DataContractJsonSerializer(
ideaScreeningError.GetType()));
// tell WCF to use JSON encoding rather than default XML
var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
//Modify response
var rmp = new HttpResponseMessageProperty
{
StatusCode = HttpStatusCode.BadRequest,
StatusDescription = "Bad Request"
};
fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
}
public bool HandleError(Exception error)
{
return true;
}
}
I can verify (via breakpoints) that the extension is being called and is executing properly. When I look at the result of the AJAX call in the browser, I can see that WCF is still returning a 500 Internal Server Error rather than the Fault details that I've specified in the error handler.
If I change Exception types being thrown in the WCF method, those are reflected in the result in the browser so I can surmise that WCF is doing something to handle the Exception and return something internally.
How do I make it stop!?
EDIT
I'm adding the custom Behavior Element:
public class ErrorBehaviorElement : BehaviorExtensionElement
{
protected override object CreateBehavior()
{
return new ErrorBehavior();
}
public override Type BehaviorType
{
get { return typeof(ErrorBehavior); }
}
}
And Behavior:
internal class ErrorBehavior : WebHttpBehavior
{
protected override void AddServerErrorHandlers(ServiceEndpoint endpoint,
EndpointDispatcher endpointDispatcher)
{
// clear default error handlers.
endpointDispatcher.ChannelDispatcher.ErrorHandlers.Clear();
// add the Json error handler.
endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(
new ErrorHandler());
}
}