Skip to content

Conversation

@hamo-o
Copy link
Contributor

@hamo-o hamo-o commented Mar 23, 2025

#️⃣ 연관된 이슈

📝 작업 내용> 이번 PR에서 작업한 내용을 간략히 설명해주세요(이미지 첨부 가능)

  1. tanstack router에서 제공하는 errorComponent를 활용하여 에러 처리를 합니다. (아래 사진 참조)
  2. tanstack query의 재시도 횟수를 1번으로 바꾸고, 해당 과정에서 handleError를 통해 네트워크 에러의 경우에만 다시 에러를 던지도록 하여 전체 UI가 블로킹되지 않도록 합니다.
  3. Error Boundary를 구현하여, 필요한 경우 UI를 감싸 부분적으로 적용할 수 있도록 합니다.
  • 예를 들어, DatePicker에서 에러를 발생시켰을 때 에러바운더리로 감싸면 다음과 같은 폴백이 적용됩니다.

    image
  • 감싸지 않으면 tanstack router로 에러가 바로 던져져, 에러 폴백 페이지가 바로 보여집니다.

    image
  1. handleError에서 올바르게 리다이렉트가 되도록 합니다.
    이전에는 tanstack-routerredirect의 쓰임을 제대로 파악하지 못해, 리다이렉트가 적용되지 않았습니다. (beforeLoadloader에서만 쓰임) 컴포넌트 외부에서 라우팅을 시키기 위해 window.location.href를 사용했는데 더 좋은 방법이 있다면 알려주세요!
image

🙏 여기는 꼭 봐주세요! > 리뷰어가 특별히 봐주었으면 하는 부분이 있다면 작성해주세요

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Introduced a clear, user-friendly notification for network issues.
    • Enhanced error pages with dynamic messaging to differentiate client and server issues.
    • Added a new error boundary component for improved error handling.
  • Enhancements
    • Optimized data fetching with added retry logic and updated network settings for improved reliability.
    • Refined error handling to provide more targeted user alerts.
    • Simplified the login view by streamlining its navigation.
    • Added functionality to efficiently clear all notifications.
    • Included a new utility to compare data arrays, aiding in state management.

@hamo-o hamo-o added the 🖥️ FE Frontend label Mar 23, 2025
@hamo-o hamo-o added this to the 7️⃣ 7차 스프린트 milestone Mar 23, 2025
@hamo-o hamo-o requested a review from dioo1461 as a code owner March 23, 2025 21:43
@coderabbitai
Copy link

coderabbitai bot commented Mar 23, 2025

Walkthrough

This PR introduces a series of enhancements to the frontend's error handling and network functionality. It adds a new network error message constant and a dedicated error class while implementing an ErrorBoundary component in both class and functional styles. The QueryClient configuration is updated to include retry logic and specific error handling. Additionally, UI components such as the ErrorPage and Login route are modified, and new utility functions for notifications and array comparison are added. The fetch module now throws a NetworkError for network issues.

Changes

File(s) Change Summary
frontend/src/constants/error.ts, frontend/src/utils/error/Errorboundary.tsx, frontend/src/utils/error/NetworkError.ts, frontend/src/utils/error/handleError.ts, frontend/src/utils/error/index.ts Introduced error handling enhancements: added NETWORK_ERROR_MESSAGE constant, implemented a new NetworkError class, created an ErrorBoundary (class & functional) with type definitions, updated handleError logic (including microtask for closeAllNoti), and exported the new error module.
frontend/src/main.tsx Enhanced QueryClient configuration by adding a retry option (retry: 1), setting networkMode to 'always' for queries and mutations, and introducing throwOnError with a custom error handler.
frontend/src/pages/ErrorPage/index.tsx Updated the ErrorPage component to support dynamic error types by adding an ErrorType type, errorText function, and a revised layout with a Flex container.
frontend/src/routes/__root.tsx, frontend/src/routes/login/index.lazy.tsx Modified routing: added an errorComponent property to use the ErrorPage with a server error type and removed the GlobalNavBar from the Login page.
frontend/src/store/global/notification.ts, frontend/src/utils/common/index.ts Added closeAllNoti to clear notifications and introduced isArrayDifferent to compare arrays.
frontend/src/utils/fetch/index.ts Updated the fetch flow to import NetworkError and throw a NetworkError instance instead of a generic Error during network failures.

Sequence Diagram(s)

sequenceDiagram
    participant Child as Child Component
    participant EBoundary as BaseErrorBoundary
    participant Parent as Parent Component
    Child->>EBoundary: Throw error
    EBoundary->>EBoundary: getDerivedStateFromError(error)
    EBoundary->>EBoundary: componentDidCatch(error)
    alt Fallback UI Provided
        EBoundary->>EBoundary: Render fallback using renderFallback
    else No Fallback
        EBoundary->>Child: Render children as is
    end
Loading
sequenceDiagram
    participant Fetch as executeFetch
    participant ErrHandler as handleError
    participant Notif as Notification Store
    Fetch->>ErrHandler: Error caught (HTTPError, NetworkError, etc.)
    ErrHandler->>Notif: Queue microtask to call closeAllNoti()
    alt Error is NetworkError
        ErrHandler-->>Fetch: Return true
    else Error is HTTPError
        ErrHandler->>Notif: Queue notification with error message
        ErrHandler-->>Fetch: Apply redirection logic / return false
    else Error is ZodError
        ErrHandler-->>Fetch: Return false
    else Other Error
        ErrHandler->>Notif: Queue default notification
        ErrHandler-->>Fetch: Return false
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Implement a functionally applicable ErrorBoundary for both HTTP and network errors ([#315])
Ensure redirection to the login page on 401 errors after forced access token injection ([#313])

Possibly related PRs

Suggested reviewers

  • dioo1461

Poem

Hi, I'm Bunny, hopping by,
Bringing fixes, oh so spry! 🐰
With errors caught and flow so neat,
My code leaps high on happy feet.
A network hop, a graceful bound,
In every line, joy is found!
Hip hip hooray for code profound!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5c11a7c and 5e0edc1.

📒 Files selected for processing (1)
  • frontend/src/utils/common/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/utils/common/index.ts

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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: 2

🧹 Nitpick comments (2)
frontend/src/pages/ErrorPage/index.tsx (1)

23-49: Good layout enhancements
Using a Flex container with spacing and images improves the user experience.

Consider adding a “Contact Support” link or a help button to guide users when an error occurs.

frontend/src/utils/error/Errorboundary.tsx (1)

41-81: Robust error boundary class
This approach properly captures errors, logs them via callbacks, and allows resetting.

You might provide a user-facing fallback even if ignoreError returns true, rather than throwing the error to crash the app.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9d3bedd and 5c11a7c.

📒 Files selected for processing (12)
  • frontend/src/constants/error.ts (1 hunks)
  • frontend/src/main.tsx (1 hunks)
  • frontend/src/pages/ErrorPage/index.tsx (1 hunks)
  • frontend/src/routes/__root.tsx (1 hunks)
  • frontend/src/routes/login/index.lazy.tsx (1 hunks)
  • frontend/src/store/global/notification.ts (1 hunks)
  • frontend/src/utils/common/index.ts (1 hunks)
  • frontend/src/utils/error/Errorboundary.tsx (1 hunks)
  • frontend/src/utils/error/NetworkError.ts (1 hunks)
  • frontend/src/utils/error/handleError.ts (1 hunks)
  • frontend/src/utils/error/index.ts (1 hunks)
  • frontend/src/utils/fetch/index.ts (2 hunks)
🧰 Additional context used
🧬 Code Definitions (4)
frontend/src/main.tsx (1)
frontend/src/utils/error/handleError.ts (1)
  • handleError (7-42)
frontend/src/utils/fetch/index.ts (1)
frontend/src/utils/error/NetworkError.ts (1)
  • NetworkError (3-8)
frontend/src/utils/error/handleError.ts (3)
frontend/src/store/global/notification.ts (2)
  • closeAllNoti (20-22)
  • addNoti (11-18)
frontend/src/utils/error/HTTPError.ts (1)
  • HTTPError (9-23)
frontend/src/constants/error.ts (1)
  • DEFAULT_ERROR_MESSAGE (30-30)
frontend/src/utils/error/NetworkError.ts (1)
frontend/src/constants/error.ts (1)
  • NETWORK_ERROR_MESSAGE (32-32)
🔇 Additional comments (21)
frontend/src/store/global/notification.ts (1)

20-22: Clean implementation for clearing notifications

The closeAllNoti function provides a simple and effective way to clear all notifications at once. This is a useful addition for error handling, allowing the system to reset notifications when errors occur.

frontend/src/utils/error/NetworkError.ts (1)

1-8: Well-structured custom error class

The NetworkError class follows best practices for custom error classes in JavaScript/TypeScript:

  • Properly extends the Error class
  • Calls super() with a meaningful message
  • Sets a descriptive name property

This will help with error identification and handling throughout the application.

frontend/src/utils/error/index.ts (1)

1-2: Consistent barrel exports pattern

The addition of the NetworkError export follows the existing pattern in this barrel file, making the new error class easily accessible throughout the application.

frontend/src/constants/error.ts (1)

32-32: Clear network error message constant

The added network error message provides clear information to users about server connectivity issues and includes guidance on what to do next. The constant follows the naming convention of other error messages in the file.

frontend/src/routes/login/index.lazy.tsx (1)

5-6: Component structure simplified!

The LoginPage component is now rendered directly without being wrapped in a GlobalNavBar. This simplifies the component structure and may be related to the overall error handling approach introduced in this PR.

frontend/src/routes/__root.tsx (1)

43-43: Great error handling implementation!

Adding the errorComponent properly implements server error handling with the TanStack Router. This aligns with the PR objectives of implementing error handling using errorComponent provided by the router.

By specifying the error type as 'server', you ensure users receive appropriate context-specific error messages when server-related issues occur.

frontend/src/utils/fetch/index.ts (2)

7-7: Good addition of NetworkError import

Adding the NetworkError import supports the improved error handling approach described in the PR objectives.


77-77: Improved error handling with specific error type

Replacing the generic error with a specific NetworkError type enhances error handling. This change enables more targeted error catching and handling elsewhere in the application, which supports the PR objective of "ensuring that network errors are re-thrown only during this process to prevent blocking the entire UI."

frontend/src/main.tsx (1)

23-23: Network mode set to 'always' for mutations
This ensures mutations won’t rely on stale or offline data. Looks good!

frontend/src/pages/ErrorPage/index.tsx (2)

8-15: Clear distinction between client & server errors
Defining two specific error states underlines a well-structured approach for user feedback.


17-19: User-friendly error text implementation
Mapping the error type to distinct messages makes it easy to provide precise information.

frontend/src/utils/error/handleError.ts (7)

4-5: Effective integration of closeAllNoti
Clearing notifications can avoid stacking multiple alerts.


12-12: Explicit return false for ZodError
Indicating the error is handled adds clarity to the function’s contract.


15-17: Closing notifications asynchronously
Using queueMicrotask ensures a quick, deferred call. No immediate issues here.


19-19: Potentially bypassing further error handling
Returning true for NetworkError can lead React Query to rethrow or handle differently.

Please double-check your desired behavior: if you want to trigger a retry or show a fallback, confirm that returning true aligns with the React Query flow.


21-28: Graceful redirection on HTTP errors
Conditionally redirecting for login/privilege errors is correct and user-friendly.


31-36: Standard error detection
Displaying a notification for generic Error objects helps keep users informed.


38-41: Catch-all fallback
Using the default message ensures complete coverage for unknown error types.

frontend/src/utils/error/Errorboundary.tsx (3)

1-15: Organized imports and utility references
Importing only what’s needed keeps this file clear.


16-39: Well-typed fallback and error ignore logic
Clearly defined prop types improve readability and reduce type confusion.


83-102: Intuitive functional boundary
Exposing the reset method via a ref is a neat pattern that simplifies manual resets.

Copy link
Contributor

@dioo1461 dioo1461 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고생하셨습니다~ 토스 에러바운더리 구현 저도 읽어봤는데 어렵네요 ..

이전에는 tanstack-router의 redirect의 쓰임을 제대로 파악하지 못해, 리다이렉트가 적용되지 않았습니다. (beforeLoad나 loader에서만 쓰임) 컴포넌트 외부에서 라우팅을 시키기 위해 window.location.href를 사용했는데 더 좋은 방법이 있다면 알려주세요!

// src/main.tsx
export const router = createRouter({ 
  routeTree,
  defaultPreload: 'intent',
  context: {
    queryClient,
  },
  scrollRestoration: true,
  scrollRestorationBehavior: 'instant',
  getScrollRestorationKey: (location) => {
    const paths = ['/home'];
    return paths.includes(location.pathname)
      ? location.pathname
      : location.state.key!;
  },
});

// src/utils/error/handleError.ts
import { router } from '@/main';
...
export const handleError = (error: unknown) => {
...
  if (error instanceof HTTPError) {
    queueMicrotask(() => {
      addNoti({ type: 'error', title: error.message });
    });

    if (error.isLoginError()) router.navigate({ to: '/login' });
...

위처럼 createRouter로 생성된 router 객체를 export하고, router.navigate() 사용하는 방식으로 내비게이션시킬 수 있을 것 같습니다!

ref: TanStack/router#819

@hamo-o
Copy link
Contributor Author

hamo-o commented Mar 27, 2025

고생하셨습니다~ 토스 에러바운더리 구현 저도 읽어봤는데 어렵네요 ..

이전에는 tanstack-router의 redirect의 쓰임을 제대로 파악하지 못해, 리다이렉트가 적용되지 않았습니다. (beforeLoad나 loader에서만 쓰임) 컴포넌트 외부에서 라우팅을 시키기 위해 window.location.href를 사용했는데 더 좋은 방법이 있다면 알려주세요!

// src/main.tsx
export const router = createRouter({ 
  routeTree,
  defaultPreload: 'intent',
  context: {
    queryClient,
  },
  scrollRestoration: true,
  scrollRestorationBehavior: 'instant',
  getScrollRestorationKey: (location) => {
    const paths = ['/home'];
    return paths.includes(location.pathname)
      ? location.pathname
      : location.state.key!;
  },
});

// src/utils/error/handleError.ts
import { router } from '@/main';
...
export const handleError = (error: unknown) => {
...
  if (error instanceof HTTPError) {
    queueMicrotask(() => {
      addNoti({ type: 'error', title: error.message });
    });

    if (error.isLoginError()) router.navigate({ to: '/login' });
...

위처럼 createRouter로 생성된 router 객체를 export하고, router.navigate() 사용하는 방식으로 내비게이션시킬 수 있을 것 같습니다!

ref: TanStack/router#819

저도 이거 시도해 봤었는데, routercontextqueryClient를 내려주고 있는데, 이 routerqueryClient에서 사용하게 되면 순환참조가 되어서 예상대로 동작하지 않더라구요...

@hamo-o hamo-o merged commit 2d9b308 into dev Mar 29, 2025
1 check passed
@hamo-o hamo-o deleted the feature/fe/error-boundary branch March 29, 2025 04:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🖥️ FE Frontend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] 에러바운더리 구현 [Bug] 액세스 토큰 강제 주입 후 401 에러 발생 시 로그인 페이지 리다이렉트 되지 않음

3 participants