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.
getRootCause()? That should return the original JDBC exception