architectureexceptionrepository-pattern

Why do Examples of the Repository Pattern never deal with Database Connection Exceptions?


I've read a lot of tutorials and seen a lot of code samples regarding implementations of the Repository pattern. In pretty much every case, exceptions that would result from attempting to hit the database when the database is unavailable is not addressed. This seems strange considering that this is a very realistic scenario if the DB is somewhere on a network.

What is the best practice for handling these exceptions?


Solution

  • I honestly think that it isn't addressed because of the ongoing (and emotional) debate about what to do with exceptions. There is a constant back and forth over whether exceptions should be handled locally (where there is a greater chance of understanding them and doing something intelligent, like retrying) or handled at the UI layer (where 99.9% of exceptions eventually bubble up to).

    Personally, I find it most elegant to do the try/catch inside the Repository layer, to catch the database-specific exceptions, and throw a new exception of my own making. That gives me a place to put retry logic. I can also then make the decision about whether that DAOException is a checked or a runtime exception.

    This allows the user interface to deal with a known exception, and it helps me to isolate my higher-level layers from any provider-specific errors. For example, if I was migrating my data store to a No-SQL database like Mongo or Cassandra, I could still throw the same exceptions, and maintain their semantic meaning, without changing all the calling code.