在启动过程中连接数据库失败后,如何捕捉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和其他一些工具。
提前感谢!
发布于 2020-07-30 22:44:36
检查您的application.properties:
spring.datasource.url = jdbc:postgresql://localhost:5432/database_name
spring.datasource.username = postgres
spring.datasource.password = postgreshttps://stackoverflow.com/questions/63161434
复制相似问题