Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Api 2: BadRequest with custom error model

The BadRequest method available on ApiController only accepts a string:

// Summary:
//     Creates an System.Web.Http.Results.ErrorMessageResult (400 Bad Request) with
//     the specified error message.
//
// Parameters:
//   message:
//     The user-visible error message.
//
// Returns:
//     An System.Web.Http.Results.InvalidModelStateResult with the specified model
//     state.
protected internal virtual BadRequestErrorMessageResult BadRequest(string message);

Why is there no overload which accepts an custom error model T?

For example, I might want to return a code along with the message:

{
    message: "Error message",
    code: "1000",
}

I could just do the following but I suspect there must be an underlying reason (perhaps in accordance with RESTful standards?):

return Content(HttpStatusCode.BadRequest, errorModel);
like image 890
Dave New Avatar asked Dec 12 '14 07:12

Dave New


1 Answers

Not sure if this is still relevant, as the question is more than 2 years old... Still, the way to do it is indeed using

return Content(HttpStatusCode.BadRequest, errorModel);

Having a standardized model for errors to include detailed information is actually a pretty good practice. See also here: API Best Practices: Response Handling

like image 197
Andrei Matracaru Avatar answered Oct 17 '22 15:10

Andrei Matracaru