【问题标题】:Spring Data Startup Exception HandlingSpring Data 启动异常处理
【发布时间】:2020-07-29 19:51:23
【问题描述】:

在启动期间无法连接到数据库后,如何捕获 Spring 引发的异常?我想让错误消息对用户友好。

例如,如果密码不正确,则抛出以下内容:

org.postgresql.util.PSQLException: FATAL: password authentication failed for user "cikfedlekqbuk"
    at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:525) ~[postgresql-42.2.14.jar:42.2.14]
    at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:146) ~[postgresql-42.2.14.jar:42.2.14]
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:197) ~[postgresql-42.2.14.jar:42.2.14]
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.2.14.jar:42.2.14]
...

或者如果格式不正确,就会抛出这个:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.RuntimeException: Driver org.postgresql.Driver claims to not accept jdbcUrl, jdbc:postgresql://url:port
... Stack trace
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.RuntimeException: Driver org.postgresql.Driver claims to not accept jdbcUrl, jdbc:postgresql://url:port
... Stack trace
Caused by: java.lang.RuntimeException: Driver org.postgresql.Driver claims to not accept jdbcUrl, jdbc:postgresql://url:port
... Stack trace

我遇到的两种可能的解决方案是使用@ExceptionHandler 或使用AOP。然而,两者都失败了,因为 @ExceptionHandler 是 MVC 特定的,并且 AOP 无法识别这些方法。这是我尝试过的切入点示例:

@AfterThrowing(value="execution(* org.springframework.boot.autoconfigure.orm.jpa.*())", throwing="e")

我也尝试过com.zaxxer.hikari.util.DriverDataSource 和其他人。

提前致谢!

【问题讨论】:

  • 你使用的postgres连接字符串是什么?

标签: java spring postgresql spring-boot hibernate


【解决方案1】:

检查您的 application.properties:

spring.datasource.url = jdbc:postgresql://localhost:5432/database_name
spring.datasource.username = postgres
spring.datasource.password = postgres

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2017-11-28
    • 2014-02-04
    • 1970-01-01
    • 2015-10-18
    • 2010-09-14
    • 1970-01-01
    相关资源
    最近更新 更多