title: Return custom error objects in Web API
body: <p>I have a web API I'm working on using the MVC 4 Web API framework. If there is an exception, I'm currently throwing a new HttpResponseException. ie:</p>
  
  <pre><code>if (!Int32.TryParse(id, out userId))
      throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid id")); 
  </code></pre>
  
  <p>This returns an object to the client that is simply <code>{"message":"Invalid id"}</code></p>
  
  <p>I would like to gain further control over this response to exceptions by returning a more detailed object. Something like </p>
  
  <pre><code>{
   "status":-1,
   "substatus":3,
   "message":"Could not find user"
   }
  </code></pre>
  
  <p>How would I go about doing this? Is the best way to serialize my error object and set it in the response message? </p>
  
  <p>I've also looked into the <code>ModelStateDictionary</code> a bit and have come up with this bit of a "hack", but it's still not a clean output:</p>
  
  <pre><code>var msd = new ModelStateDictionary();
  msd.AddModelError("status", "-1");
  msd.AddModelError("substatus", "3");
  msd.AddModelError("message", "invalid stuff");
  throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, msd));
  </code></pre>
  
  <p><strong>edit</strong><br>
  looks like a custom <code>HttpError</code> is what I need. This seems to do the trick, now to make it extensible from my business layer... </p>
  
  <pre><code>var error = new HttpError("invalid stuff") {{"status", -1}, {"substatus", 3}};
  throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, error));
  </code></pre>