Search code examples
spring-bootjdbctemplatesqlexception

JDBCtemplate doesn't allow catch SQLException


I'm using Spring JDBC and I've got this test method to connect to PostgreSQL DB (It's a example code, this isn't the original code):

public void toConnect() {
    final String sql = "SELECT 1";
    template.execute(sql);
}

If I catch the DataAccessException, and I call method getCause() the program trigger the PLSQException anyway (though finally printing the message that I set in the catch).

public void toConnect() throws CGConnException {
    final String sql = "SELECT 1";
    try {
        template.execute(sql);
    } catch (DataAccessException e) {
        throw new CGConnException("CG : Error DataBase connection. - ", e.getCause());
    }
}

The problem is than I can't handle the exception and I want than only print the Message of the catch, without the exception details.

If it's run with an error on config parameters or the PostgreSQL database is down, a PSQLException is generated and that is great but I need to control this exception. However JdbcTemplate.execute(sql) method throws a DataAccessException, therefore, doesn't possibly catch the PSQLException on try/catch block (or I don't know how to do). So, when run the program always appears the stack trace in the console:

2021-05-02 03:10:14.052 ERROR 73837 --- [           main] .PostgresClientTestConnectionApplication : Error : CG : Error DataBase connection.

In this case, I need to print only a log as "Connection Error" or something similar as the example above.

Thank you in advance.


Solution

  • Actually there is no mistake. The exception is handled and the program finally correctly when is catch it.

    try {
        template.execute(sql);
        logger.error("Connection Successful . . .");
    } catch (Exception e) {
        logger.error("Error connection" + e.getMessage());
        throw new CGConnException("CG : Error DataBase connection. - ", e);
    }
    

    In the run console it's print the associate stack trace because Spring internal classes to do it, but don't mean than we are doing something wrong or than no handle the exception.