35
In my web API using the MVC 4 Web API framework, if there is an exception I'm throwing a new HttpResponseException:
if (!Int32.TryParse(id, out userId))
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid id"));
This returns an object to the client: {"message":"Invalid id"}. I want to return a more detailed object:
{
"status":-1,
"substatus":3,
"message":"Could not find user"
}
How would I go about this? Is the best way to serialize my error object and set it in the response message? I've looked into ModelStateDictionary and came up with this, but it's not a clean output:
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));