-
Notifications
You must be signed in to change notification settings - Fork 0
[REFACTOR] Axios 코드 및 API 오류 처리 보강 #324
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: develop
Are you sure you want to change the base?
Conversation
WalkthroughAxios 인스턴스와 오류 처리 로직이 전면적으로 리팩터링되었습니다. API 오류를 위한 커스텀 에러 클래스가 도입되고, ErrorBoundary 및 ErrorPage 컴포넌트가 실제 Error 객체를 처리하도록 변경되었습니다. HTTP 상태 코드별 메시지 상수와 delay 유틸 함수가 추가되었으며, Vite 개발 서버 포트가 3000으로 명시되었습니다. Changes
Sequence Diagram(s)sequenceDiagram
participant Component
participant ErrorBoundary
participant ErrorPage
participant API
participant APIError
Component->>API: request()
API-->>Component: (정상 응답)
API--x Component: (에러 발생)
Component->>ErrorBoundary: throw error
ErrorBoundary->>ErrorPage: error 객체 전달
ErrorPage->>APIError: (APIError 인스턴스면 상태코드 메시지 표시)
Suggested labels
Suggested reviewers
Poem
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
npm error Exit handler never called! ✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (2)
src/util/delay.ts (1)
1-3
: 매개변수 이름 개선 및 타입 안전성 강화 필요매개변수 이름이 함수 이름과 동일하여 혼란을 야기할 수 있습니다. 또한 음수 값에 대한 검증이 없어 예상치 못한 동작이 발생할 수 있습니다.
다음과 같이 개선할 수 있습니다:
-export default function delay(delay: number) { - return new Promise((res) => setTimeout(res, delay)); +export default function delay(ms: number) { + if (ms < 0) { + throw new Error('Delay time must be non-negative'); + } + return new Promise<void>((resolve) => setTimeout(resolve, ms)); }src/components/ErrorBoundary/ErrorPage.tsx (1)
22-25
: ERROR_STATUS_TABLE 키 존재 여부 확인 추가 권장APIError의 status 코드가 ERROR_STATUS_TABLE에 존재하지 않는 경우를 대비한 안전장치를 추가하는 것이 좋겠습니다.
다음과 같이 개선할 수 있습니다:
const title = error instanceof APIError - ? ERROR_STATUS_TABLE[error.status] + ? ERROR_STATUS_TABLE[error.status] || `${error.status} 오류` : '오류가 발생했어요...';
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
src/apis/axiosInstance.ts
(1 hunks)src/apis/primitives.ts
(2 hunks)src/components/ErrorBoundary/ErrorBoundary.tsx
(3 hunks)src/components/ErrorBoundary/ErrorPage.stories.tsx
(2 hunks)src/components/ErrorBoundary/ErrorPage.tsx
(2 hunks)src/constants/errors.ts
(1 hunks)src/util/delay.ts
(1 hunks)vite.config.ts
(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/components/ErrorBoundary/ErrorPage.stories.tsx (1)
src/apis/primitives.ts (1)
APIError
(9-19)
src/apis/axiosInstance.ts (1)
src/util/accessToken.ts (1)
getAccessToken
(5-7)
src/components/ErrorBoundary/ErrorPage.tsx (2)
src/apis/primitives.ts (1)
APIError
(9-19)src/constants/errors.ts (1)
ERROR_STATUS_TABLE
(1-10)
🔇 Additional comments (22)
src/constants/errors.ts (1)
1-10
: 깔끔한 HTTP 상태 코드 매핑 구현HTTP 상태 코드를 한국어 메시지로 매핑하는 구현이 잘 되어 있습니다.
Record<number, string>
타입과as const
어서션을 적절히 사용하여 타입 안전성과 불변성을 보장했습니다.vite.config.ts (1)
19-19
: 개발 서버 포트 명시적 설정개발 서버 포트를 3000으로 명시적으로 설정하여 일관된 개발 환경을 보장하는 좋은 개선사항입니다.
src/components/ErrorBoundary/ErrorPage.stories.tsx (2)
3-3
: APIError 임포트 추가새로운 APIError 클래스를 임포트하여 스토리에서 사용할 수 있도록 했습니다.
15-27
: 스토리 업데이트가 적절히 수행됨기존 Default 스토리는 Error 객체를 사용하도록 업데이트되었고, 새로운 OnAPIError 스토리는 APIError 클래스의 사용법을 잘 보여줍니다. 두 스토리 모두 스택 트레이스를 포함하여 완전한 오류 정보를 제공합니다.
src/components/ErrorBoundary/ErrorPage.tsx (5)
4-5
: 필요한 임포트 추가APIError 클래스와 ERROR_STATUS_TABLE 상수를 임포트하여 향상된 오류 처리 로직을 구현했습니다.
8-8
: 인터페이스 개선Props 인터페이스가
message: string
에서error: Error
로 변경되어 더 풍부한 오류 정보를 처리할 수 있게 되었습니다.
20-25
: 향상된 오류 제목 로직APIError 인스턴스인지 확인하여 HTTP 상태 코드에 따른 적절한 오류 메시지를 표시하는 로직이 잘 구현되었습니다. ERROR_STATUS_TABLE을 활용한 조건부 제목 설정이 사용자 경험을 크게 개선합니다.
44-44
: 오류 메시지 표시 개선문자열 메시지에서
error.message
를 사용하도록 변경하여 더 정확한 오류 정보를 사용자에게 제공합니다.
17-17
: 네비게이션 경로 유효성 확인 완료
'/home'
경로는src/routes/routes.tsx
(17번 줄)에 다음과 같이 정의되어 있어 유효합니다.
- src/routes/routes.tsx:17 →
path: '/home'
추가 조치 없이 변경된 경로를 그대로 사용하셔도 됩니다.
src/apis/axiosInstance.ts (5)
8-9
: 환경 모드 감지 로직 개선 승인
currentMode
변수를 통한 환경 감지는 깔끔하고 명확합니다. 테스트 환경에서 실제 API 요청을 방지하는 로직이 잘 구현되었습니다.
13-14
: 테스트 환경에서 baseURL 설정 개선테스트 환경에서
baseURL
을undefined
로 설정하여 실제 API 요청을 방지하는 것은 좋은 접근입니다. MSW와 같은 모킹 도구와 잘 연동될 것입니다.
15-17
: 타임아웃 설정 및 사용자 친화적 메시지타임아웃을 5초로 줄이고 한국어 메시지를 추가한 것은 좋은 UX 개선입니다. 5초는 적절한 타임아웃 값으로 보입니다.
21-21
: withCredentials 설정 개선전역 기본값 대신 인스턴스 수준에서
withCredentials
를 설정하는 것이 더 나은 캡슐화입니다.
24-35
: 주석 추가로 가독성 향상요청/응답 인터셉터에 주석을 추가하여 코드의 가독성이 향상되었습니다.
src/apis/primitives.ts (4)
8-19
: APIError 클래스 구현 우수API 오류를 캡슐화하는
APIError
클래스가 잘 설계되었습니다.status
와data
속성을 통해 풍부한 오류 정보를 제공하고,readonly
속성으로 불변성을 보장합니다.
33-36
: axios 설정 명시적 할당
method
,data
,params
속성을 명시적으로 할당하는 것이 더 명확하고 읽기 쉽습니다.
42-51
: 향상된 오류 처리 로직Axios 오류를
APIError
로 래핑하는 로직이 잘 구현되었습니다. 응답 데이터, 상태 코드, 메시지를 모두 포함하여 상위 컴포넌트에서 풍부한 오류 정보를 활용할 수 있습니다.
53-54
: 비-Axios 오류 처리Axios 오류가 아닌 경우 그대로 재throw하는 것이 적절한 오류 처리 방식입니다.
src/components/ErrorBoundary/ErrorBoundary.tsx (4)
10-14
: Error 객체 기반 상태 관리 개선
ErrorBoundaryState
인터페이스를 문자열 메시지에서Error
객체로 변경한 것은 우수한 개선입니다.defaultError
상수로 일관성 있는 오류 처리가 가능합니다.
27-30
: getDerivedStateFromError 메서드 개선
Error
객체를 직접 저장하여 상위 컴포넌트에서 더 풍부한 오류 정보를 활용할 수 있게 되었습니다. 특히 새로운APIError
클래스와 잘 연동될 것입니다.
38-44
: resetError 메서드 일관성
defaultError
를 사용하여 상태를 초기화하는 것이 새로운 Error 객체 기반 접근 방식과 일관성이 있습니다.
49-50
: ErrorPage 컴포넌트 연동 개선
Error
객체를ErrorPage
에 전달하여 더 상세한 오류 정보 표시가 가능해졌습니다. 새로운APIError
클래스의 상태 코드와 데이터를 활용할 수 있을 것입니다.
🚩 연관 이슈
closed #322
📝 작업 내용
🔔 알립니다
현재 이슈 #310 코드가 너무 많아서, 팀원 여러분께서 리뷰를 조금 더 편하게 하실 수 있도록 PR을 더 세부적으로 쪼개고 있습니다. 총 3개 PR로 나누어질 예정이며, 이 PR은 1번째 PR입니다.
문제 상황
개선 사항
Axios 코드 다듬기
Axios 관련 코드들에 다음과 같은 변경 사항을 적용하였습니다:
npm run dev
환경에서 DEV 서버 API를 사용할 수 있게 개선undefined
로 지정되도록 명시2번 항목은 PR #321 참고하여 작업 진행하였습니다. (사실상 병합한 것과 다를 바 없음) 또한, 2번 항목 적용할 경우 제 환경에서는 테스트 진행 시 msw로 모방된 데이터가 들어오는 게 아니라 실제 DEV 서버로 요청이 가는 문제가 있어, 테스트 환경에서의 URL도 명시적으로
undefined
로 지정하였습니다.API 요청 중 발생한 오류 처리 보강
API 요청 중 발생한 오류를
APIError
로 따로 처리하고,ErrorBoundary
및ErrorPage
에서도APIError
가 들어올 경우 오류 코드와 간단한 설명 - 예를 들어, 404 Not Found라던지 - 을 같이 표기하도록 개선하였습니다.그 외 변경사항
로딩 중 UI가 잘 출력되는지 확인할 목적으로, src/util/delay.ts에 딜레이 함수를 추가했습니다.
🏞️ 스크린샷 (선택)
500 Internal Server Error
404 Not Found
🗣️ 리뷰 요구사항 (선택)
없음