title: How to consume/parse an error returned by ASP.NET WebApi?
body: <p>According to <a href="http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx" rel="nofollow">this blog post</a>, I can create an error response in my ApiController, that provides useful information to the client, like this:</p>
  
  <pre><code>    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format("Contact {0} not found.", id)));
  </code></pre>
  
  <p>... and the client will receive an "object" containing the error details along with the (in this example) 404 status:</p>
  
  <pre><code>{
       "Message": "Contact 22 not found.",
       "MessageDetail": "&lt;other info - not always present&gt;"
  }
  </code></pre>
  
  <p>(I don't think that <code>MessageDetail</code> is appropriate in this example, and so would probably not be included, but under other circumstances it might be - see the blog post).</p>
  
  <p>Sounds great, but how should my C# client-side application <em>consume</em> this on the client side? I made a request, I was expecting a JSON-encoded <code>Contact</code> object in response, but instead I got a different type of object.</p>
  
  <p>Because the response code indicated a failure, then I guess I know not to expect the <code>Contact</code> object, and to look instead for this error object. But given that not every error will return one of these, and also given that the <code>MessageDetail</code> member may or may not be present, how do I go about parsing the response? (Note: in my scenario, it'll be JSON-encoded, and I'm using JSON.NET on the client side).</p>
  
  <p>If the object was of a well-known type, then I could just use <code>JsonConvert.DeserializeObject&lt;T&gt;()</code>, but I don't think there's a pre-defined type, and if I create my own class what do I do about the optional <code>MessageDetail</code> member?</p>
  
  <p>I'm not very familiar with processing JSON, so this may be obvious to those who are - in which case all advice gratefully received.</p>