ASP.NET Core Web API Interview Question #122

How should an API handle DbUpdateException?

Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate

Quick Interview Answer

DbUpdateException indicates a failure while persisting changes and may wrap provider-specific errors such as constraint violations. Log diagnostic information securely and translate only understood, expected cases into meaningful API responses.

Detailed Explanation

DbUpdateException indicates a failure while persisting changes and may wrap provider-specific errors such as constraint violations. Log diagnostic information securely and translate only understood, expected cases into meaningful API responses.

Do not expose raw SQL exceptions or database details to clients. Unknown failures should flow through centralized exception handling and become safe server-error responses.

Code Example

try
{
    await _db.SaveChangesAsync(token);
}
catch (DbUpdateException ex)
{
    _logger.LogError(ex, "Failed to save product");
    throw;
}