Рекомендации по возврату ошибок в веб-API ASP.NET

У меня есть опасения по поводу того, как мы возвращаем ошибки клиенту.

Возвращаем ли мы ошибку немедленно, бросая HttpResponseException, когда получаем ошибку:

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) 
    }
}

Или мы накапливать все ошибки, а затем отправлять обратно клиенту:

public void Post(Customer customer)
{
    List errors = new List();
    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>(errors, HttpStatusCode.BadRequest);
    throw new HttpResponseException(responseMessage);
}

Это всего лишь пример кода, не имеет значения ни ошибки проверки, ни ошибки сервера, я просто хотел бы узнать о лучших практиках, плюсах и минусах каждого подхода

. ]

364
задан Guido Leenders 10 May 2018 в 22:53
поделиться