简体   繁体   中英

Exceptions handling EF Core 2.0

I'm using EF Core 2.0 with Repository and Unit of Work patterns. What is the best way to handle all db exceptions?. Can I just use try/catch in my commit method?

public void Commit()
{
    try
    {
        _context.SaveChanges();
    }
    catch (Exception ex)
    {
         //code
    }
}

Can anything beyond SaveChanges() throw an exception? What should do next with caught exception?

If you look at the SaveChanges documentation , it suggests that only 2 types of exceptions will ever be thrown by SaveChanges: DbUpdateException and DbUpdateConcurrencyException . These are EF-specific exceptions, and their inner exceptions will contain provider-specific exceptions.

So you should at least explicitly catch those, but what you do with them is up to you... you should definitely at least log the errors somewhere at some point. The generic exception catch block should only be used for truly unexpected cases, but things like the network being down are not really unexpected.

Another exception to keep in mind is DbUpdateException , which is an abstract class that is implemented by the EF provider (SqlServer, DB2, etc...) and from what I've seen it will be thrown by methods like BeginTransaction , Commit , etc... So maybe handle that one as well. It's easy to forget that these other methods can also throw exceptions in case the connection is broken, not just SaveChanges.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM