throwing meaningful exceptions from hibernate DAO implementation
In my web application(jsp+hibernate+hsqldb on tomcat) code, I am using couple of Dao implementations.The base class Dao implementation contains all the session open,close logic.A number of domain specific Dao classes extend this base class to provide specific find(),delete() methods
I wanted to give the user meaningful messages when an error occurs ,instead of a error500 message . Since,the base class method uses a hibernate.Session class for get(),saveOrUpdate() methods ,they throw HibernateException.The domain specific subclasses need 开发者_StackOverflow社区to catch this an wrap it in some Custom Exception and rethrow it.
I tried it this way..I don't know if this is the correct way to do it..I would welcome your opinion/suggestions
sincerely,
Jim
abstract class BaseDao{
private Class persistentClass;
public BaseDao(Class persistentClass) {
super();
this.persistentClass = persistentClass;
}
public Object findById(Long id) {
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
Object object = null;
try {
object = (Object) session.get(persistentClass, id);
return object;
}
finally {
session.close();
}
}
@Override
public void saveOrUpdate(Object obj) {
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(obj);
tx.commit();
}catch(HibernateException e){
if (tx != null) {
tx.rollback();
}
throw e;
}finally {
session.close();
}
}
}
The domain specific dao is
class SaleOrderDao extends BaseDao{
public SaleOrderDao() {
super(SaleOrder.class);
}
@Override
public SaleOrder findSaleOrderById(Long saleOrderId){
SaleOrder so = (SaleOrder)findById(saleOrderId);
return so;
}
@Override
public void saveOrUpdateSaleOrder(SaleOrder so){
try{
saveOrUpdate( so);
}catch(HibernateException e){
String msg = "could not insert/update saleorder"+so.getSONumber();
throw new SaleOrderDaoException(msg+"/ "+e.getMessgae());
}
}
}
Are you sure that customer want to have meaningful message? I believe that meaningful error should appear just in case of business errors. For technical (read, unexpected) errors customer should see just generic error page, probably with error reference code, but no more that that.
Another problem with your code is you are going to include e.getMessage into error message. It is not good, because, potentially, that message can have some technical information, which may help to break into your system. But, saying that, logs have to have as much information as possible (within sensible limits, there shouldn't be passwords, card details) about the error.
So the basic rule - for technical errors show to customer as least as you can. Business errors are the other story, here you should be as clear as possible.
精彩评论