问题
When scaffolding a new ApiController
with asynchronous actions and Entity Framework support in Visual Studio 2013, some methods wrap DbContext.SaveChangesAsync calls in try-catch
blocks.
For instance, the Put method,
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!EmployeeExists(id))
{
return NotFound();
}
throw;
}
From msdn.microsoft.com about DbUpdateConcurrencyException
,
Exception thrown by DbContext when it was expected that SaveChanges for an entity would result in a database update but in fact no rows in the database were affected.
The DbUpdateConcurrencyException
is derived from DbUpdateException
and there are a handful of other exceptions that can be thrown from the DbContext.SaveChangesAsync
method.
I'm wondering why there are no catch clauses for these other exceptions? Is it for the sake of brevity? Or do they simply not belong at this level in the application?
回答1:
The Web API scaffolding controller follows REST semantics, so a PUT is effectively an update of a record.
The MSDN message states that the exception is thrown if a record was not updated so in this case it will throw an exception if the record failed to be updated. If the record did not exist, a 404 not found is returned.
In summary, although an exception is thrown by the database, it may be a valid case in the context of a REST service (no update performed because the record did not exist) and not a real error. The other exceptions will be bubbled up to the client.
来源:https://stackoverflow.com/questions/30004291/dbcontext-savechangesasync-exception-handling