Reputation: 834
I am working on a spring MVC application. I have a DAO, Service and Controller. In Dao, I have a method which queries database to return a Sql rowset. I am checking sql rowset to be empty and if it is, I am throwing a Runtime exception. Also, according to the logic of the application, the query to database should return at least one row. So, basically I am assuming that if I get an empty sql rowset, then there is some issue, may be database is corrupt or something similar.
Is this the correct way to check for unknown exceptions. Or should I return the sql rowset as it is to the service? It may result in a null pointer exception when service uses this sql rowset.
The problem is if I throw exception in dao, I can't cover that part in the test cases. Means I have to put db in inconsistent state for this code to execute and test the exception handling part.
Upvotes: 0
Views: 1706
Reputation: 8137
No, more generally you should never introduce a restriction into your application just because you don't have that situation or requirement right now. If you don't have any rows in a database your database might just be empty... Or you may be doing testing on that schema and it is currently empty. Your violating the concern of the dao by doing that.
Furthermore don't worry about the database, that is senseless. If you can't accept the tools you are working are functioning correctly then you won't be able to build anything at all. If you want to handle database exceptions have a controller which catches these exceptions and redirects to a view showing an error message:
@ControllerAdvice
public class ErrorHandler {
@ExceptionHandler(DataAccessException.class)
public String handleDatabaseException(DataAccessException ex) {
return "error";
}
@ExceptionHandler(CannotCreateTransactionException.class)
public String handleAccessException(CannotCreateTransactionException ex) {
return "database_error";
}
}
Upvotes: 2
Reputation: 52205
The DAO layer should not concern itself with business rules. It should simply abstract the data operations so that the service layer does not need to concern itself with how and where is the data being stored.
In my opinion, the DAO should simply return an empty result set. It will be up to the service to know what to do with an empty result set, since at the service layer is usually where the business logic is stored.
Upvotes: 1