【问题标题】:Catch a Hibernate exception upon SpringBoot application startup?在 Spring Boot 应用程序启动时捕获 Hibernate 异常?
【发布时间】:2016-01-29 18:28:17
【问题描述】:

我正在尝试将 Spring Boot 1.2.6 与 HibernateJpaAutoConfiguration 一起使用。效果很好;那就是它由 entityManager “神奇地”创建,并使用我的 spring.jpa.* 属性为我完成所有配置。

但是,如果出现数据库错误(无效凭据、数据库不可访问等),我找不到在启动时捕获 Hibernate 异常的干净方法。

我想我可以捕获所有的 BeanCreationException 并检查根本原因,但这似乎是一个 hack:

    ConfigurableApplicationContext context;
    try {
        SpringApplication app = new SpringApplication(Application.class);
        context = app.run(args);
    } catch (Exception e) {
        // check if it is a DB error.  
        if( ExceptionUtils.getRootCause(e) instanceof( HibernateException ) ){
            System.out.println( "You are having trouble with the DB: " + ExceptionUtils.getRootCauseMessage(e) );
        }
    }
    finally{
        // finished so close the context
        if( context != null )
            context.close();
    }

有没有一种更简洁/更整洁的方式来做到这一点而不会失去使用自动配置的能力?此外,如果不解析错误消息,有没有办法确定 Hibernate/DB 错误是什么(即:无效的凭据、未验证的数据库等)。

【问题讨论】:

    标签: java spring hibernate spring-boot


    【解决方案1】:

    您可以尝试捕获JDBCConnectionException,而不是捕获非常通用的HibernateException。这是HibernateException 的子类,用于解决数据库连接问题(包括不正确的数据库设置)。

    https://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/exception/JDBCConnectionException.html

    【讨论】:

    • 问题出在main()层面,其实是Spring BeanCreationException。此外,BeanCreationException 的根本原因只是一个普通的 HibernateException。这就是为什么我试图找到一种更好的方法来做到这一点。我无法在此级别捕获 JDBCConnectionException。
    • getMostSpecificCause() 方法返回什么?该方法存在于 NestedRuntimeException(BeanCreationException 的父级)中。
    • getMostSpecificCause() 仍然显示 HibernateException:(org.hibernate.HibernateException) org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set。即使我可以在更高的堆栈跟踪中看到 2015-10-30 12:12:00,571 ERROR ConnectionPool - Unable to create initial connections of pool. java.sql.SQLException: Access denied for user 'eric'@'localhost' (using password: YES)
    • @JackTheKnife 不...我不相信我这样做了,只是留下了一条通用错误消息。糟糕的解决方案,但当时找不到更好的方法
    猜你喜欢
    • 1970-01-01
    • 2020-10-29
    • 2020-06-24
    • 2021-08-18
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多