Back-end/spring boot
PSQLException 예외처리 - getCause()와 getSQLState() 활용해 DB 연결, data insert 예외처리 | PSQLException exception handling - DB connection and data insertion using getCause() and getSQLState() [spring boot]
은성 개발자
2024. 8. 15. 02:06
728x90
검색해도 Postgresql의 exception인 PSQLException 예외처리는 잘 안 나왔다.
그래서 PSQLException 예외 처리를 위해 getCause()랑 getSQLState()를 해봤다.
[ 전제 상황 ]
- jpa 말고 preparedStatement (pstmt) 사용
- datasource.getConnection()으로 연결 시도
- DB 연결을 시도 했을 때 exception 처리 부분
- PSQLException에서 추적한 exception은 ConnectionException 밖에 없었다.
- ConnectionException은 DB 서버가 꺼졌을 때 발생한다.
- db 사용자명, 비밀번호, 권한이 다를 때는 getCause()나 getSQLState()에서 반응하지 않아 PSQLException까지만 도달했다.
catch (SQLException e) {
if(e.getCause() instanceof PSQLException){
if(e.getCause().getCause() instanceof ConnectException){
log.error("Postgresql DB connection fail: DB server is not exist :{}",e.getMessage());
}else{
log.error("Postgresql DB connection fail: Check username, password, authority .etc :{}",e.getMessage());
}
}
else {
log.error("SQLException 발생: {}",e.getMessage(),e);
}
}
2. insert를 시도할 때 (이거는 자세하게는 안 했으니 참고)
- 여기서는 getCause()보다는 getSQLState()에서 가능했다
- 22003 ⇒ data type range가 넘어갔을 때, 예를 들자면.. INTEGER 크기의 값을 SMALLINT에 넣었을 때
- 23502 ⇒ 기존 column 칼럼이 null → not null로 변경 또는 새로운 column이 not null이라서 null값이 데이터로 들어왔을 때
- 그 외에도 많을 수도 있다.
catch (PSQLException e){
String sqlState = e.getSQLState();
if(sqlState.equals("22003")){
log.error("Postgresql DB의 data가 range에서 벗어남 : {}",e.getMessage());
}
else if(sqlState.equals("23502")){
log.error("Postgresql DB column이 not null로 change / not null인 new column 추가!! {}", e.getMessage());
}
}
728x90
반응형