I'm implementing a RESTful web service using WCF by WebHttpBinding, and working on the custom error handler (IErrorHandler). The aim is to catch all exceptions and return a JSON error object. Here's the code I'd implemented in ProvideFault method of my error handler:
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
fault = Message.CreateMessage(version, "", new CustomMsg { code = "99", msg = "error" }, new DataContractJsonSerializer(typeof(CustomMsg)));
var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
var rmp = new HttpResponseMessageProperty
{
StatusCode = HttpStatusCode.OK
};
rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
}
It's working for any other exception except the scenario below: When giving a wrong json format of request body like missing a double quotation or a comma, that would cause deserializing error caught by ProvideFault method(got NetDispatcherFaultException), but finally I got the unexpected html error(http status code 400) rather than json format. Is there any way to handle it?
Customize error handler by implementing IErrorHandler and expect that it return JSON format object(http status code 200) to the client especially when the client trying to give a wrong json format of request body.