If I have a layered application and my Data Layer may encounter an OptimisticConcurrencyException how should the calling layer or indeed the lower layer deal with this??

The calling layer has no idea what an OptimisticConcurrencyException is, so should I be implementing a custom exception and catching the OptimisticConcurrencyException and throwing my Custom Exception?

2 Answers
2

OptimisticConcurrencyException is an exception that belongs to the data layer and should therefore be contained within it. It's unlikely that calling layer could handle it.

I would create a more generic exception such as DataSourceException which would contain some context such as which function failed (and with which parameters) and why. I would also include the original exception as inner exception.

My UI is MVVM, I want my ViewModel to advise the user that the record was updated by another user and perform some navigation accordingly, but what type of exception do I catch? In that layer it would only be able to identify the exception as a System.Exception.
–
DavidDec 17 '10 at 19:41

In this case, create an exception which indicates that the record changed. For instance EntityChangedByOtherException or something like that. Follow the Seperated Interface pattern found here: martinfowler.com/eaaCatalog/separatedInterface.html to reduce coupling between the layers.
–
jgauffinDec 17 '10 at 19:57

@jgauffin, thanks again for reply. Are you suggesting that I implement for example EntityChangedByOtherException (which would inherit from System.Exception) in the assembly/layer that would throw it and define an interface for it in another assembly e.g. IEntityChangedByOtherException which my VM would use?
–
DavidDec 17 '10 at 21:09

You need to look at this from the perspective of the calling layer. The layer has asked the data layer to perform a job. If the OptimisticConcurrencyException can be handled by your data layer and the contract adhered to, then by all means catch it and then carry on and complete the job.

If, however, this is fatal to the job you're being asked to do, and if the caller is not expecting it, or doesn't know it, then it's fine for you to create your own exception class, catch the exception that is alien to the calling layer, and throw that instead. This is something that the calling layer can know about, and can be well-documented as a side-effect of using this function/API.