Passing exceptions between logical layers

Assume you have a layered system, build-up using the separation of concerns principle. We have a UI layer, a services layer and a database layer. The UI layer communicates with a service layer, which communicates with a database layer. As the names describe, the UI layer is responsible for showing an UI to the user, the services take care of main logic of the application and the data access layer communicates internally with a database.

Our UI, services and data access layer.

What if within the database access layer, an SqlException refering to a Microsoft SQL database is thrown. This can happen for example due to the fact an invalid value was tried to be written to the database. First of all by not catching this exception within the layer itself and letting it go through the services layer, we pollute in a sense the services layer. The services layer have to know it is dealing with a Microsoft SQL database. So here we break our separation of concerns principle.

What will it cost us if we break this separation of concern? Well, what if we change the SQL database by for example an web-server? If the database layer didn’t catch the database exception, it ends up in the services layer. So if we replace the SQL with the web server, we need to handle web exceptions also in the services layer.

It would be easier to just have a generic exception at the data access layer, which catches all detailed exceptions underneath it and wraps it up in a more user friendly exception as seen from an client which uses the data access layer. See it like you would do in an API.

Benefits by throwing a, let-say, data-access exception is that we now can easily change the internals of our data access layer without having to change the interface.

Posted in Best practices, C# by Bruno at July 19th, 2019.
Tags: ,

Leave a Reply