I have concerns on the way that we returns errors to client.
Do we return error immediately by throwing HttpResponseException when we get an error:
public void Post(Customer customer)
{
if (string.IsNullOrEmpty(customer.Name))
{
throw new HttpResponseException("Customer Name cannot be empty", HttpStatusCode.BadRequest)
}
if (customer.Accounts.Count == 0)
{
throw new HttpResponseException("Customer does not have any account", HttpStatusCode.BadRequest)
}
}
Or we accumulate all errors then send back to client:
public void Post(Customer customer)
{
List<string> errors = new List<string>();
if (string.IsNullOrEmpty(customer.Name))
{
errors.Add("Customer Name cannot be empty");
}
if (customer.Accounts.Count == 0)
{
errors.Add("Customer does not have any account");
}
var responseMessage = new HttpResponseMessage<List<string>>(errors, HttpStatusCode.BadRequest);
throw new HttpResponseException(responseMessage);
}
This is just a sample code, it does not matter either validation errors or server error, I just would like to know the best practice, the pros and cons of each approach.
For Web API 2 my methods consistently return IHttpActionResult so I use...
It looks like you're having more trouble with Validation than errors/exceptions so I'll say a bit about both.
Validation
Controller actions should generally take Input Models where the validation is declared directly on the model.
Then you can use an
ActionFilter
that automatically sends valiation messages back to the client.For more information about this check out http://ben.onfabrik.com/posts/automatic-modelstate-validation-in-aspnet-mvc
Error handling
It's best to return a message back to the client that represents the exception that happened (with relevant status code).
Out of the box you have to use
Request.CreateErrorResponse(HttpStatusCode, message)
if you want to specify a message. However, this ties the code to theRequest
object, which you shouldn't need to do.I usually create my own type of "safe" exception that I expect the client would know how to handle and wrap all others with a generic 500 error.
Using an action filter to handle the exceptions would look like this:
Then you can register it globally.
This is my custom exception type.
An example exception that my API can throw.
For me I usually send back a
HttpResponseException
and set the status code accordingly depending on the exception thrown and if the exception is fatal or not will determine whether I send back theHttpResponseException
immediately.At the end of the day its an API sending back responses and not views, so I think its fine to send back a message with the exception and status code to the consumer. I currently haven't needed to accumulate errors and send them back as most exceptions are usually due to incorrect parameters or calls etc.
An example in my app is that sometimes the client will ask for data, but there isnt any data available so i throw a custom noDataAvailableException and let it bubble to the web api app, where then in my custom filter which captures it sending back a relevant message along with the correct status code.
I am not 100% sure on whats the best practice for this, but this is working for me currently so thats what im doing.
Update:
Since i answered this question a few blog posts have been written on the topic:
http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx
(this one has some new features in the nightly builds) http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx
Update 2
Update to our error handling process, we have two cases:
For general errors like not found, or invalid parameters being passed to an action we return a HttpResponseException to stop processing immediately. Additionally for model errors in our actions we will hand the model state dictionary to the
Request.CreateErrorResponse
extension and wrap it in a HttpResponseException. Adding the model state dictionary results in a list of the model errors sent in the response body.For errors that occur in higher layers, server errors, we let the exception bubble to the Web API app, here we have a global exception filter which looks at the exception, logs it with elmah and trys to make sense of it setting the correct http status code and a relevant friendly error message as the body again in a HttpResponseException. For exceptions that we aren't expecting the client will receive the default 500 internal server error, but a generic message due to security reasons.
Update 3
Recently, after picking up Web API 2, for sending back general errors we now use the IHttpActionResult interface, specifically the built in classes for in the System.Web.Http.Results namespace such as NotFound, BadRequest when they fit, if they dont we extend them, for example a notfound result with a response message:
You can throw a HttpResponseException
Use the built in "InternalServerError" method (available in ApiController):
If you are using ASP.NET Web API 2, the easiest way is to use the ApiController Short-Method. This will result in a BadRequestResult.