英文:
Errorhandling in post
问题
我目前正在编写一个.NET 6 Web API。我必须实现一个保存项目列表的方法。我编写了以下的POST方法来实现这个功能:
[HttpPost]
public IActionResult PostCustomer(List<Customer> customers)
{
foreach (var customer in customers)
{
SaveCustomer(customer);
}
return Ok();
}
SaveCustomer()
方法进行了许多验证,可能会引发错误。因此,有可能某个客户无法保存。如果我在 SaveCustomer()
周围添加一个 try-catch,那么其他客户都会被保存。但响应没有告诉我由于错误而无法保存某个客户。我该如何创建一个正确的响应,类似警告的方式?
类似这样的响应:警告:无法保存客户 x。
英文:
I am currently writing a NET 6 web API. I have to implement a method which saves a list of items. I wrote the following POST-Method to do that:
[HttpPost]
public IActionResult PostCustomer(List<Customer> customers)
{
foreach (var customer in customers)
{
SaveCustomer(customer);
}
return Ok();
}
The SaveCustomer()
method makes a lot of validation and could throw an error. So it is possible, that a customer cannot be saved. If I am adding a try-catch around SaveCustomer()
, all other customers are saved. But the response is not telling me, that one customer couldn't be saved because of an error. How can I create a correct response, like a warning?
Something like this: Warning: Customer x is not saved
答案1
得分: 2
你可以在响应中返回一个失败客户列表,并将失败客户的对象详情(如ID或姓名)添加到其中。
List<string> failedCustomers { get; set; }
foreach (var customer in customers)
{
try
{
SaveCustomer(customer);
}
catch (Exception ex)
{
failedCustomers.Add(customer.Id);
}
}
if (failedCustomers.Any())
{
return StatusCode(StatusCodes.Status207MultiStatus, failedCustomers);
}
else
{
return Ok();
}
请注意响应代码Status207MultiStatus
,参考此问题。
英文:
you can return a list of failed customers in the response and add the failed customer object details to this (like id or name).
List<string> failedCustomers { get; set; }
foreach (var customer in customers)
{
try
{
SaveCustomer(customer);
}
catch (Exception ex)
{
failedCustomers.Add(customer.Id);
}
}
if (failedCustomers.Any())
{
return StatusCode(StatusCodes.Status207MultiStatus, failedCustomers);
}
else
{
return Ok();
}
Pay attention to the response code Status207MultiStatus
, refer to this question.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论