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?

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
McThrok
  • 27
  • 1
  • 8
  • 3
    If you add exception handling on such low level (especially catching base Exception), you will hide possible db connection issues from yourself and any other exception which could happen – Darjan Bogdan Aug 29 '18 at 08:07
  • 1
    Firstly EF already is a UoW and Repository Pattern, making your own (9 times out of 10) is redundant and more trouble than its worth, in regards to exception handling in general, catch what you know / expect (***and can handle***), let the rest propagate up. There is no one size fits all approach – TheGeneral Aug 29 '18 at 08:18
  • 1
    EF DbContext implements Unit of Work pattern, DbSet implements Repository pattern – Vladi Pavelka Aug 29 '18 at 08:23

1 Answers1

0

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.

Shahin Dohan
  • 6,149
  • 3
  • 41
  • 58