Best Practice, Fehler in der ASP.NET -Web -API zurückzugeben [geschlossen]
Posted: 15 May 2025, 20:51
Ich habe Bedenken hinsichtlich der Art und Weise, wie wir Fehler an den Client zurückgeben.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)
}
}
< /code>
Oder wir sammeln alle Fehler an und senden dann an den Client zurück: < /p>
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);
}
< /code>
Dies ist nur ein Beispielcode. Es spielt keine Rolle, weder Validierungsfehler noch Serverfehler, ich würde nur gerne die Best Practice, die Vor- und Nachteile jedes Ansatzes kennen. < /p.>
{
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)
}
}
< /code>
Oder wir sammeln alle Fehler an und senden dann an den Client zurück: < /p>
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);
}
< /code>
Dies ist nur ein Beispielcode. Es spielt keine Rolle, weder Validierungsfehler noch Serverfehler, ich würde nur gerne die Best Practice, die Vor- und Nachteile jedes Ansatzes kennen. < /p.>