views:

50

answers:

2

An easy one that I am interested in getting your thoughts on:

With your repository implementations, do you like to let exceptions be thrown inside the repository and leave the exception handling to the caller, or do you prefer to catch exceptions inside your repository, store the exception and return false/null?

+1  A: 

It Depends.

Do I let exceptions bubble up? Absolutely. But I want this for connection failure, command failures. Whatever you do, don't just hide these, you need to know about them. I prefer my applications to fail as quickly as possible to reduce side-effects and further damage.

I also log exceptions. I use Log4net to help with this. But I like to log exceptions at the source. I will let them bubble up from there.

Return null? If something cannot be found (i.e. looking for something by id and it isn't there), then I return null, not an exception. But there are cases where I could see throwing a new exception when this happens.

Main point: exceptions should be 'exceptional', not the rule. If an exception is thrown, it should be because something is really wrong and you need to fix it.

Chris Brandsma
Your main point I think is very valid. +1
Nathan Ridley
A: 

I usually let exceptions leak, though if I'm in a particularly Enterprisey mood I'll wrap them in a RepositoryException to keep clients from caring about the underlying storage engine.

I would never return false/null instead of an exception, as there's already a meaning behind those values.

In rare cases, you could have a brain-dead storage engine that generates exceptions on non-exceptional cases - and I would catch those specific ones and return null if appropriate (eg., if a row does not exist, but the storage engine throws an error on that case - I'd catch it and return null).

Mark Brackett
Yeah, I'm with you on only catching errors that are related to non-exceptional cases. It occurred to me that if I caught exceptions inside the repository and returned false, all I was doing was forcing myself to remember to to trap the errors outside the repository, which ultimately would amount to the same thing in the user experience anyway. (assuming I'm catching errors and failing gracefully)
Nathan Ridley