Я пытаюсь удалить запись из базы данных, используя jpa данных spring в базе данных postgresql, и мне нужно зафиксировать код ошибки sql.
try {
userRepository.deleteUser(id);
} catch(org.springframework.dao.DataAccessException e) {
// here
}
Как получить код ошибки sql в блоке catch? Метод getCause или getMessage не получает код ошибки sql
Большое спасибо, это работает с getRootCause




В официальный JavaDoc интерфейса SQLExceptionTranslator мы находим эту подсказку:
The returned DataAccessException is supposed to contain the original
SQLExceptionas 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, agetRootCause() instanceof SQLExceptioncheck (and subsequent cast) is considered reliable when expecting JDBC-based access to have happened.
Итак, имея в виду эту информацию, вы можете написать такой код:
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...
}
}
Надеюсь это поможет.
Большое спасибо, он отлично работает с приведенным выше кодом.
А как насчет
getRootCause()? Это должно вернуть исходное исключение JDBC