-
RestTemplate은 4xx를 예외로 처리한다.프레임워크/Spring Boot 2024. 5. 2. 02:25
RestTemplate 사용 중에 서버로부터 응답이 반환되어도 예외가 발생하는 것이 낯설어 기록하여봅니다.
다음의 순서로 작성되었습니다.
1. 응답 객체의 형태
2. 404를 반환 받을 때
1. 응답 객체의 형태
현재 User 서버는 Request를 받아서 실행 중에 이슈가 생기면 advice를 통해서 적절한 응답을 반환하고 있습니다.
성공 케이스와 실패 케이스 모두 동일한 인터페이스를 사용해서 반환하고 있습니다.
성공인 경우 result에 데이터가 들어가고, 예외가 발생한 경우는 error에 에러 객체를 넣어서 전달합니다.
2. 404를 반환받을 때
이상함을 느낀 코드는 아래와 같습니다.
restTemplate을 사용해서 User 데이터를 가져오려고 하고 있습니다.
요청한 유저가 존재하지 않는 경우를 처리하기 위해서 잘못된 id로 요청을 넣고 첫번째 if 문에 걸려서 예외가 발생할 것이라고 생각했습니다.
if (Objects.nonNull(result.getError())) { throw new UsernameNotFoundException("유저 데이터를 가져오는 중 문제가 발생하였습니다. [이유: " + result.getError().getMessage() + "]"); }
하지만 if 문에 걸리지 않고 바로 catch문에서 예외가 잡혀버립니다.
(서버에서 응답으로 전달하는 내용들은 잘 들어있습니다.)
공식문서를 찾아봤지만 4xx 시리즈를 예외로 처리한다고 명시되어있는 부분은 못찾았습니다.
하지만 4xx 번 때 status 코드의 응답을 받으면 예외로 처리하는 듯 보입니다.
4xx의 응답도 응답 자체는 무사히 전달 받았으니 예외로 처리하는게 적절한가? 하는 생각이 듭니다 ㅎㅎ
성공 이외의 것은 catch에서 처리할 것을 염두에 두고 설계된 것으로 느껴지기도 합니다 ㅎㅎ
아무튼 예외 처리할 때 참고해야겠습니다!
감사합니다.
'프레임워크 > Spring Boot' 카테고리의 다른 글
SecurityFilterChain을 여러개 쓰고자 한다면 securityMatcher! (0) 2024.05.03 RestTemplate는 응답 객체를 LinkedHashMap으로 파싱한다 (0) 2024.05.02 SpringBootApplication이 필요한 bean을 찾지 못하는 경우 (0) 2024.04.25 N + 1 정복하기 <5. Entity Graph> (0) 2024.02.21 N + 1 정복하기 <4. @BatchSize> (0) 2024.02.21