开发者

How to treat exceptions in hibernate?

I'm using hibernate and this looks like for the most of my methods:

public boolean insertUser(User user) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();
    } catch (HibernateException he) {
        session.getTransaction().rollback();
        return false;
    } finally {
        if (session != null) {
            session.close();
        }
    }

    return true;
}

But I would like to treat the exceptions in a better way to give a better message to the user开发者_运维问答, e.g: when I have a duplicate key in my table, and etc.

What you guys recommend ?

Best regards, Valter Henrique.


  • whatever you do, don't swallow exceptions. In your code you will never know what the exception is. So rethrow it/a wrapper. And log it somewhere (might not necessarily be in the above code)

  • make a generic exception handler in the web layer - might be a Filter, or a 404 error page (and configure it in web.xml). And show the same message to users regardless of the exception. Users don't really care if it's a missing column or a wrong datatype. Give them a nice message that you are sorry and you'll be investigating.

  • also consider declarative transaction handling, as offered by spring.


Instead of returning true or false you can throw business exception of your own (probably a hierarchy over RuntimeException that makes sense for your problem at hand).

How you detect what the exact issue was is another problem. You can rollout your own exception translator which depending on the SQLException will throw an appropriate (specific to your business) exception.

Note though, that for this specific method you present it'd be better to query the database for existence of the key first and throw the UserAlreadyExistsException (or something).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜