I need some guidance on how to send error responses to client from WebAPI controller for an update operation. I need to check if data is changed and if it has duplicate data. I have service class that does database operations.
Below is psuedo code
Approach 1
CustomerController.cs
public Task<IActionResult> UpdateCustomer(int id, Customer request)
{
var customer = service.GetCustomer(id);
if(customer is null)
return NotFound()
var isChanged = service.IsChanged(request, customer);
if(!isChanged)
return BadRequest();
var isDuplicate = service.IsDuplicate(request);
if(!isDuplicate)
return BadRequest(); //500 error
await service.Update(request)
}
Approach 2
CustomerController.cs
public Task<IActionResult> UpdateCustomer(int id, Customer request)
{
var customer = service.GetCustomer(id);
if(customer is null)
return NotFound()
await service.Update(request, customer);
}
CustomerService.cs
public void Update(Customer request, Customer customer)
{
if(!HasChanged(request, customer))
throw NoChangesException();
if(IsDuplicate(request))
throw DuplicateException();
db.Update(request);
}
Catch exceptions in Global exception Middleware and send the BadRequest or Internal error based on exception type.
Edit
I need to add that duplicates and no changes will be rejected by data layer. Its the functionality acrossData layer is another common databaseOData service. So we know that these exceptions occur if we submitI feel its expensive to call the requestdata service for known exceptions.