在启动过程中和启动之后处理Spring Boot中的数据库连接错误

时间:2019-05-25 07:05:56

标签: java hibernate spring-boot spring-data-jpa

我在application.properties中具有以下配置:

spring.datasource.url=jdbc:postgresql://localhost:5432/demodb
spring.datasource.username=postgres
spring.datasource.password=password
spring.session.store-type=jdbc
spring.session.jdbc.initialize-schema=always
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update

我想正常处理数据库连接错误,并且由于数据库连接失败,应用程序不应停止工作。

我希望应用程序在启动期间和启动之后都处理错误。

我的数据库关闭时出现以下异常:

Caused by: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:245) ~[postgresql-42.2.2.jar:42.2.2]
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.2.2.jar:42.2.2]
    ...
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[na:1.8.0_172]
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) ~[na:1.8.0_172]
    ...

在@ControllerAdvise中,我尝试在启动后处理错误,但未捕获到异常:

@ControllerAdvice
public class AppAdvise {

    @ResponseBody
    @ExceptionHandler(PSQLException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AppResponse psqlExceptionHandler(PSQLException ex) {
        return helpers.getResponseErrorObject(ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(JDBCConnectionException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AppResponse psqlExceptionHandler(JDBCConnectionException ex) {
        return helpers.getResponseErrorObject(ex.getMessage());
    }
}

在启动时和启动后如何处理连接错误?

0 个答案:

没有答案