Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 4802

Best practice to return errors in ASP.NET Web API

$
0
0

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.


Viewing all articles
Browse latest Browse all 4802

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>