DbContext.SaveChangesAsync Exception Handling

若如初见. 提交于 2021-02-10 07:23:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!