Reputation: 85
I am working on a new Spring MVC based application. I have multiple flows where the controller will make request to business manager and further business manager will talk to DAO layer to retrieve data.
There can be possible cases where I don't get data back from the DAO. I want to understand what is best way to deal with this situation.
1) When ever there is no data retrieved for a query then Throw back Custom Exception like 'Content Not Found' from DAO layer to Business Layer and then to Controller and let controller decide what to do.
2) Return blank/null Pojo object back to business manager and let manager throw the exception to Controller.
3) Controller receives null/blank from Manager and decides what to do with that.
I am finding 1st approach better as when the exception is thrown i have complete stack trace to understand where exactly the problem occurred but on downside I will end up cluttering my code with Exception in the signatures.
Number 3 will leave the code clean but I wont be able to pin point where exactly the data retrieval failed as there can be multiple calls to DAO from Business Layer.
Upvotes: 1
Views: 1444
Reputation: 26828
The DAO layer executes queries and returns the results. It doesn't care about the results, so "nothing found" cannot be an exceptional situation in the DAO layer. It can be in the business layer, but it doesn't have to.
I wont be able to pin point where exactly the data retrieval failed
If your use case is http://server/something/2
and something 2
doesn't exist in the database, then there simply is no failure on the server side. So if there is no exception, or only one in the controller, then you can be pretty confident that no data is returned to the client because no data exists.
Upvotes: 2
Reputation: 13181
Throw an exception on the level where the situation of not having matching records (in other words, no data to be processed) actually is exceptional.
This largely depends on the specifics of your domain, but it's often the best idea to simply return an empty container object from the DAO if there was no matching object in the database. That is: an Collections.emptyList()
, Optional.empty()
or something with similar semantics. Under no circumstances return null
, it's 2015 after all.
If having no matching data is an exceptional situation in your business domain, translate that to a specific exception in the service layer and let the controller handle that by translating again: into an error HTML page, some specific XML or JSON response or whatever the interface your users use to interact with your system.
Upvotes: 2
Reputation: 3872
I would suggest you to throw custom exceptions at each layer. Each layer should be aware of exception handling.
Its beautifully explained in the below link.
Handling Dao exceptions in service layer
Upvotes: 1