1

I am trying to delete a record from database using spring data jpa on postgresql database and I need to capture the sql error code

try {
    userRepository.deleteUser(id);
} catch(org.springframework.dao.DataAccessException e) {
    // here
}

How do I get the sql error code in catch block? getCause or getMessage method is not retrieving sql error code

2
  • What about getRootCause()? That should return the original JDBC exception Commented Jul 30, 2019 at 7:23
  • Thanks a lot, it is working with getRootCause Commented Aug 2, 2019 at 2:24

1 Answer 1

4

In the official JavaDoc of the interface SQLExceptionTranslator we find this hint:

The returned DataAccessException is supposed to contain the original SQLException as root cause. However, client code may not generally rely on this due to DataAccessExceptions possibly being caused by other resource APIs as well. That said, a getRootCause() instanceof SQLException check (and subsequent cast) is considered reliable when expecting JDBC-based access to have happened.

So, with this information in mind, you can write code like this:

try {
    userRepository.deleteUser(id);

} catch(org.springframework.dao.DataAccessException e) {
    if( e.getRootCause() instanceof SQLException) {
        SQLException sqlEx = (SQLException) e.getRootCause();
        int sqlErrorCode = sqlEx.getErrorCode();
        // do further things from here on...
    }
}

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, it is working fine with the above code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.