HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaspringMinor

Managing data access layer exceptions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
exceptionslayermanagingdataaccess

Problem

I am developing a webapp using Spring MVC + Hibernate. I created a GenericDao class that implements basic data access methods, to be extended by all my concrete daos in the app. What I want advice or review about is the exception handling of the data access layer exceptions. Let me post a shortened version of my generic Dao class:

```
public class GenericDaoHibernateImpl extends AbstractDaoHibernateImpl implements
GenericDao {

private Class entityClass;

@SuppressWarnings("unchecked")
public GenericDaoHibernateImpl() {
this.entityClass = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}

public Class getEntityClass() {
return entityClass;
}

public void saveOrUpdate(E entity) throws GenericDataBaseException {
try {
getSession().saveOrUpdate(entity);
} catch (Throwable t) {
Collection args = new ArrayList();
args.add(entity);
throw exceptionHandler.handle(this, t, "saveOrUpdate", args);
}
}

public void delete(PK id) throws GenericDataBaseException, InstanceNotFoundException {
try {
getSession().delete(findById(id));
} catch (InstanceNotFoundException t) {
throw t;
} catch (Throwable t) {
Collection args = new ArrayList();
args.add(id);
throw exceptionHandler.handle(this, t, "delete", args);
}
}

@SuppressWarnings("unchecked")
public E findById(PK id) throws GenericDataBaseException, InstanceNotFoundException {
try {
E entity = (E) getSession().get(entityClass, id);

if (entity == null)
throw new InstanceNotFoundException(id, entityClass.getName());

return entity;
} catch (InstanceNotFoundException t) {
throw t;
} catch (Throwable t) {
Collection args = new ArrayList();
args.a

Solution

I would say don't set rules like "I will catch exceptions in this layer."
With exceptions you have two options catch them or throw them. If you know what to do with exception then catch it and proccess it in the catch section. If you dont know what to do at the current level(layer) throw it. Of course the last line of defence is before the view layer where you should catch the ones that you didn't managed to catch in the other layers and show somethin meaningful to the user.

Context

StackExchange Code Review Q#30719, answer score: 2

Revisions (0)

No revisions yet.