java 如何正确捕获、包装和重新抛出 Hibernate 异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7656714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:51:31  来源:igfitidea点击:

How to properly catch, wrap and re-throw a Hibernate exceptions?

javahibernateexception

提问by Alex Abdugafarov

My database worker is implemented above the Hibernate. If something goes wrong, it's methods should rollback the transaction and throw an SQLException. So my question is: what is the best (i.e. cleanest) way to handle Hibernate exceptions? Currently all my methods looks as ugly as this:

我的数据库工作者是在 Hibernate 之上实现的。如果出现问题,它的方法应该回滚事务并抛出一个SQLException. 所以我的问题是:处理 Hibernate 异常的最佳(即最干净)方法是什么?目前我所有的方法看起来都像这样丑陋:

public EntryUserHib addUser(final String username, final String pwdhash) throws SQLException{
    try {
        final Transaction ta = sess.beginTransaction();
        try {
            // Using Hibernate here
            // "return" statement
        } catch(final HibernateException ex) {
            try {
                ta.rollback();
            } catch(final Exception ex1) {}
            throw ex;
        } finally {
            if (!ta.wasRolledBack()) ta.commit();
        }
    } catch(final HibernateException ex) {
        if (ex.getCause() != null) {
            if (ex.getCause() instanceof SQLException) throw (SQLException)ex.getCause();
            throw new SQLException(ex.getCause());
        }
        throw new SQLException(ex);
    }
}

采纳答案by Ryan Stewart

Let someone else manage it for you, like Spring. It has extensive Hibernate and transaction supportthat will extract all of that code that you're worried about.

让其他人为您管理它,例如 Spring。它具有广泛的 Hibernate 和事务支持,可以提取您担心的所有代码。

回答by RichW

Don't catch them at all. Hibernate exceptions extend RuntimeException for two good reasons: you don't have to declare them in method signatures, and any RuntimeException automatically causes a rollback of the transaction. Exception-handling makes for very cluttered code. The Hibernate folks have the philosophy that HibernateExceptions should be fatal errors, signaling coding or logic errors, and in a properly-function application should not be (and doesn't need to be) caught.

根本不要抓住他们。Hibernate 异常扩展 RuntimeException 有两个很好的原因:您不必在方法签名中声明它们,并且任何 RuntimeException 都会自动导致事务回滚。异常处理导致代码非常混乱。Hibernate 人员的理念是 HibernateExceptions 应该是致命错误、信号编码或逻辑错误,并且在功能正常的应用程序中不应该(也不需要)被捕获。

Your application's UI should respond to these surprises in a user-friendly way, though. That's a separate issue.

不过,您的应用程序的 UI 应该以用户友好的方式响应这些意外。那是一个单独的问题。