错误处理在发布中

huangapple go评论75阅读模式
英文:

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&lt;Customer&gt; 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&lt;string&gt; 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.

huangapple
  • 本文由 发表于 2023年1月9日 17:45:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055462.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定