Exception Handling in a Layered Application
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?
Some guidance on this would be greatl开发者_运维知识库y appreciated.
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.
Read my blog entry about catching exceptions: http://blog.gauffin.org/2010/11/do-not-catch-that-exception/
I've also written some other entries about exception handling, click on the Exception tag.
Update
I would create the following projects:
- Project.Web <--- uses service through the specification interfaces.
- Project.Service <-- implements everything in Specification
- Project.Service.Specification <--- Place exceptions (classes) here and interfaces defining your services (or repositories if you do not use any services).
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.
精彩评论