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.
Just to update on the current state of ASP.NET WebAPI. The interface is now called
IActionResult
and implementation hasn't changed much:For those errors where modelstate.isvalid is false, I generally send the error as it is thrown by the code. Its easy to understand for the developer who is consuming my service. I generally send the result using below code.
This sends the error to the client in below format which is basically a list of errors:
ASP.NET Web API 2 really simplified it. For example, the following code:
returns the following content to the browser when the item is not found:
Suggestion: Don't throw HTTP Error 500 unless there is a catastrophic error (for example, WCF Fault Exception). Pick an appropriate HTTP status code that represents the state of your data. (See the apigee link below.)
Links:
Building up upon
Manish Jain
's answer (which is meant for Web API 2 which simplifies things):1) Use validation structures to response as many validation errors as possible. These structures can also be used to response to requests coming from forms.
2) Service layer will return
ValidationResult
s, regardless of operation being successful or not. E.g:3) API Controller will construct the response based on service function result
One option is to put virtually all parameters as optional and perform custom validation which return a more meaningful response. Also, I am taking care not to allow any exception to go beyond the service boundary.
you can use custom ActionFilter in Web Api to validate model
}
Register CustomAttribute class in webApiConfig.cs config.Filters.Add(new DRFValidationFilters());