Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try Catch in Repository

None of the examples I have looked at for Repository Patterns include any kind of error handling. Why is this? Say for instance I have this:

public virtual TItem Insert<TItem>(TItem item) where TItem:class,new()
    {
        dbContext.Set<TItem>().Add(item);
        try
        {
            dbContext.SaveChanges();
        }
        catch (DbUpdateException)
        {

            return null;
        }

        return item;

    }

An instance where we violate a constraint. I catch the DbUpdateException... Where would this error handling live if not in the repository itself?

like image 793
Code Jammr Avatar asked Feb 03 '23 19:02

Code Jammr


1 Answers

In a properly-designed system, the constraints should never be able to be violated. Make your entities smarter: don't use blind auto-implemented setters, for example.

The repository is not the place to do data validation. The proper place is:

  • If you are checking simply "contractual" constraints, e.g. "quantity should be a nonnegative integer" or "don't pass me a null customer," put the logic in the entity itself (either setters or constructor or mutating methods, as appropriate).
  • If you are checking business logic, put it in specialized objects (DDD specifications if you wish) that abstract away that logic.

The only time these exceptions should come up is when you run your unit integration tests and you get a failure, which will reveal that either your database constraints are mismatched with your entity, or your entity is implemented incorrectly. So you definitely shouldn't catch them.

like image 52
Domenic Avatar answered Feb 14 '23 09:02

Domenic