[ Home ]

Getting the Server Error Message from a SQLException

When using the PostgreSQL JDBC driver, a SQLException is also a PSQLException. You can get the same server error message that you would see if you were in a psql session. This is particularly useful when you want to check for constraint violations, because Postgres names the constraints that you violate in the server error message.

try {
    sqlMap.startTransaction();  // iBATIS
    // some sql statement
    sqlMap.commitTransaction();  // iBATIS
} catch (SQLException e) {
    boolean ok = false;
    Throwable t = e.getCause();
    if (t instanceof PSQLException) {
        PSQLException psqle = (PSQLException)t;
        String serverErrorMessage = psqle.getServerErrorMessage().getMessage();
        if ("duplicate key violates unique constraint \"my_table_pk\"".equals(serverErrorMessage)) {
            ok = true;
            log.trace("This is OK: " + serverErrorMessage + "; rolling back and moving on");
        }
    }
    if ( ! ok) {
        log.fatal("This is not good: ", e);
    }
} finally {
    try {
        sqlMap.endTransaction();
    } catch (SQLException e2) {
        log.fatal("This is not good: ", e2);
    }
}