Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Dao exceptions in service layer

If my Dao layer throws Dao specific exceptions, then does handling them in my service layer consitute a leakage of concerns? If yes, then should I make the exceptions generic and independent of any layer to address it, or is there some other way?

The same question is applicable to UI layer handling exceptions thrown by service layer.

like image 248
shrini1000 Avatar asked Feb 13 '12 06:02

shrini1000


People also ask

How do you handle exceptions in DAO layer?

don't handle any exceptions in the dao layer, instead throw it to the front-end and handle it. to handle the exception all you need to do is to catch the appropriate exception in the hierarchy and address it.

How does service layer handle exceptions?

Every layer should have however their specific exceptions as generic. for example, DAO layer may have custom exception handlers like DavaSavingException, IOException etc.. So the approach is throw exception from DAO to service layer and again throw it to UI layer and catch in UI specific classes.

Should you handle exceptions in service or controller?

Exceptions are not a good way to do it, although possible. Validations should return boolean true or false to the controller, and then the controller returns a response to the user with an explanatory message. Don't return code 500 for validations; that code is meant for server errors, not user errors.

Can we use @service in DAO layer?

By convention you can mark DAO classes with @Repository and services with @Service . Also the former does some persistence layer exception translation. Since you are asking theoretically: DAO should perform raw database operations and translate them to some higher level constructs (objects, collections).


1 Answers

When we create a layered application, there is always a user layer and another used layer. For this case UI layer -> uses service Layer -> uses DAO layer.

Now its very subjective and open to interpretations. But the objective should be a good degree of decoupling. To achieve this, one way out is the define generic layer specific exceptions say PersistentException, ServiceException etc. These exception will wrap the actual layer specific exception.

For example say if there is some error on database side (Constraint violation etc), wrap that in PersistentException and let service layer handle that (as to how to convey this to UI layer in a generic way)

Now since the integration between service layer and DAO layer is contractual (interface based), the DAO layer is free to change the implementation to anything as long as it obeys the interface contract. So if you change the implementation which throws some new exceptions, those new exceptions can be wrapped in PersistentException and Service layer remains unaffected.

like image 168
Santosh Avatar answered Oct 05 '22 23:10

Santosh