Skip to content

[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

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from

Conversation

i-meant-to-be
Copy link
Contributor

@i-meant-to-be i-meant-to-be commented Jul 18, 2025

🚩 연관 이슈

closed #322

📝 작업 내용

🔔 알립니다

현재 이슈 #310 코드가 너무 많아서, 팀원 여러분께서 리뷰를 조금 더 편하게 하실 수 있도록 PR을 더 세부적으로 쪼개고 있습니다. 총 3개 PR로 나누어질 예정이며, 이 PR은 1번째 PR입니다.

문제 상황

  • 다소 어수선한 Axios 관련 코드
  • 앱 실행 중 API에서 던져진 오류에 대한 처리가 미흡

개선 사항

Axios 코드 다듬기

Axios 관련 코드들에 다음과 같은 변경 사항을 적용하였습니다:

  1. 중복된 역할을 하는 코드 제거
  2. npm run dev 환경에서 DEV 서버 API를 사용할 수 있게 개선
  3. 테스트 환경에서는 API URL이 undefined로 지정되도록 명시

2번 항목은 PR #321 참고하여 작업 진행하였습니다. (사실상 병합한 것과 다를 바 없음) 또한, 2번 항목 적용할 경우 제 환경에서는 테스트 진행 시 msw로 모방된 데이터가 들어오는 게 아니라 실제 DEV 서버로 요청이 가는 문제가 있어, 테스트 환경에서의 URL도 명시적으로 undefined로 지정하였습니다.

API 요청 중 발생한 오류 처리 보강

API 요청 중 발생한 오류를 APIError로 따로 처리하고, ErrorBoundaryErrorPage에서도 APIError가 들어올 경우 오류 코드와 간단한 설명 - 예를 들어, 404 Not Found라던지 - 을 같이 표기하도록 개선하였습니다.

그 외 변경사항

로딩 중 UI가 잘 출력되는지 확인할 목적으로, src/util/delay.ts에 딜레이 함수를 추가했습니다.

🏞️ 스크린샷 (선택)

500 Internal Server Error

image

404 Not Found

image

🗣️ 리뷰 요구사항 (선택)

없음

@i-meant-to-be i-meant-to-be requested review from useon and jaeml06 July 18, 2025 14:14
@i-meant-to-be i-meant-to-be self-assigned this Jul 18, 2025
@i-meant-to-be i-meant-to-be added the refactor 기능 변경 없이 코드만 변경했을 경우 label Jul 18, 2025
Copy link

coderabbitai bot commented Jul 18, 2025

Walkthrough

Axios 인스턴스와 오류 처리 로직이 전면적으로 리팩터링되었습니다. API 오류를 위한 커스텀 에러 클래스가 도입되고, ErrorBoundary 및 ErrorPage 컴포넌트가 실제 Error 객체를 처리하도록 변경되었습니다. HTTP 상태 코드별 메시지 상수와 delay 유틸 함수가 추가되었으며, Vite 개발 서버 포트가 3000으로 명시되었습니다.

Changes

파일/경로 요약 변경 요약
src/apis/axiosInstance.ts 환경 모드별 baseURL 설정, timeout 단축, 한글 타임아웃 메시지 추가, withCredentials 인스턴스별 적용, 인터셉터 주석 보강 등
src/apis/primitives.ts APIError 클래스 도입, request 함수 에러 처리 개선, AxiosError 래핑 및 config 명확화, 불필요한 import 제거
src/components/ErrorBoundary/ErrorBoundary.tsx state가 message string 대신 Error 객체 저장, AxiosError 관련 처리 및 import 제거, ErrorPage에 Error 객체 전달로 변경
src/components/ErrorBoundary/ErrorPage.stories.tsx message string 대신 Error 객체 사용, stack 명시, APIError 시나리오 추가
src/components/ErrorBoundary/ErrorPage.tsx props가 message string → Error 객체로 변경, 홈 이동 경로 수정, APIError일 때 상태코드 기반 메시지 표시, 한글 메시지 적용
src/constants/errors.ts HTTP 상태코드별 한글 에러 메시지 상수 ERROR_STATUS_TABLE 추가
src/util/delay.ts delay(ms) 후 Promise 반환하는 delay 유틸 함수 추가
vite.config.ts Vite dev 서버 포트 3000으로 명시

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 인스턴스면 상태코드 메시지 표시)
Loading

Suggested labels

fix

Suggested reviewers

  • eunwoo-levi
  • katie424

Poem

🐇
에러도, API도, 이제는 걱정 마세요
한글 메시지로 친절하게 알려주고
Error 객체로 감싸 안아
토끼처럼 폴짝폴짝,
코드도 더 튼튼해졌어요!
3000번 포트에서 만나요!
🥕

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

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-07-18T14_15_41_289Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between f77cc18 and 2d3a8db.

📒 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 설정 개선

테스트 환경에서 baseURLundefined로 설정하여 실제 API 요청을 방지하는 것은 좋은 접근입니다. MSW와 같은 모킹 도구와 잘 연동될 것입니다.


15-17: 타임아웃 설정 및 사용자 친화적 메시지

타임아웃을 5초로 줄이고 한국어 메시지를 추가한 것은 좋은 UX 개선입니다. 5초는 적절한 타임아웃 값으로 보입니다.


21-21: withCredentials 설정 개선

전역 기본값 대신 인스턴스 수준에서 withCredentials를 설정하는 것이 더 나은 캡슐화입니다.


24-35: 주석 추가로 가독성 향상

요청/응답 인터셉터에 주석을 추가하여 코드의 가독성이 향상되었습니다.

src/apis/primitives.ts (4)

8-19: APIError 클래스 구현 우수

API 오류를 캡슐화하는 APIError 클래스가 잘 설계되었습니다. statusdata 속성을 통해 풍부한 오류 정보를 제공하고, 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 클래스의 상태 코드와 데이터를 활용할 수 있을 것입니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactor 기능 변경 없이 코드만 변경했을 경우
Projects
Status: No status
Development

Successfully merging this pull request may close these issues.

[REFACTOR] Axios 코드 및 오류 처리 로직 보강
1 participant