Search code examples
c#webapihttp-status-codes

Errorhandling in post


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


Solution

  • 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.