title: REST WCF Service with IErrorHandler catches SerializationExceptions
body: <p>I have a REST WCF service with a custom IErrorHandler, so that I can catch all uncaught exceptions in my service and return a custom error message, a proper Http status code (500) and log the error. </p>
  
  <p>The problem is that the IErrorHandler will catch exceptions not originating from my code, so if I for example make a POST to the service with invalid JSON data, I will get a SerializationException. That exception would have been transformed into a WebFaultException with status code BadRequest 400, if it weren't for my IErrorHandler, where I will handle it just like all other uncaught exceptions.</p>
  
  <p>Is there a way of dealing with these situations or should I just catch SerializationExceptions in my IErrorHandler and set BadRequest there? What other exceptions might orginate from the WCF stack without coming from my code? </p>
  
  <p><strong>Update:</strong> Added my implementation of IErrorHandler.ProvideFault</p>
  
  <pre><code> public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
      {
          Guid loggingId = Guid.NewGuid();
          error.Data["ExceptionLoggingId"] = loggingId;
  
          if (error is SecurityTokenException)
          {
              fault = Message.CreateMessage(version, string.Empty, String.Format("{0}. The error identifier is {1}", error.Message, loggingId), new DataContractJsonSerializer(typeof(string)));
              fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
  
              webOperationContextWrapper.SetOutgoingResponseStatusCode(HttpStatusCode.Unauthorized);
          }
          else
          {
              if (error is SerializationException)
              {
                  // TODO: What if the SerializationException originates from within the service?
                  // SerializationException due to malformed JSON
                  return;
              }
  
              fault = Message.CreateMessage(version, string.Empty, String.Format("An unknown error has occurred. The error identifier is {0}", loggingId), new DataContractJsonSerializer(typeof(string)));
              fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
  
              webOperationContextWrapper.SetOutgoingResponseStatusCode(HttpStatusCode.InternalServerError);
          }
  }
  </code></pre>