-
Notifications
You must be signed in to change notification settings - Fork 1
[FE-Feat] Tanstack Query 커스텀 에러 설정, handleError 개선, 에러 바운더리 구현 #348
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
Conversation
WalkthroughThis 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
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
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
Assessment against linked issues
Possibly related PRs
Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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: 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
ignoreErrorreturnstrue, rather than throwing the error to crash the app.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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 notificationsThe
closeAllNotifunction 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 classThe
NetworkErrorclass 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 patternThe 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 constantThe 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
LoginPagecomponent is now rendered directly without being wrapped in aGlobalNavBar. 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
errorComponentproperly implements server error handling with the TanStack Router. This aligns with the PR objectives of implementing error handling usingerrorComponentprovided 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 importAdding the
NetworkErrorimport supports the improved error handling approach described in the PR objectives.
77-77: Improved error handling with specific error typeReplacing the generic error with a specific
NetworkErrortype 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 ofcloseAllNoti
Clearing notifications can avoid stacking multiple alerts.
12-12: Explicitreturn falsefor ZodError
Indicating the error is handled adds clarity to the function’s contract.
15-17: Closing notifications asynchronously
UsingqueueMicrotaskensures a quick, deferred call. No immediate issues here.
19-19: Potentially bypassing further error handling
ReturningtrueforNetworkErrorcan 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
truealigns 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 genericErrorobjects 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.
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.
고생하셨습니다~ 토스 에러바운더리 구현 저도 읽어봤는데 어렵네요 ..
이전에는 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
저도 이거 시도해 봤었는데, |
#️⃣ 연관된 이슈
📝 작업 내용> 이번 PR에서 작업한 내용을 간략히 설명해주세요(이미지 첨부 가능)
tanstack router에서 제공하는errorComponent를 활용하여 에러 처리를 합니다. (아래 사진 참조)tanstack query의 재시도 횟수를 1번으로 바꾸고, 해당 과정에서handleError를 통해 네트워크 에러의 경우에만 다시 에러를 던지도록 하여 전체 UI가 블로킹되지 않도록 합니다.Error Boundary를 구현하여, 필요한 경우 UI를 감싸 부분적으로 적용할 수 있도록 합니다.예를 들어,
DatePicker에서 에러를 발생시켰을 때 에러바운더리로 감싸면 다음과 같은 폴백이 적용됩니다.감싸지 않으면
tanstack router로 에러가 바로 던져져, 에러 폴백 페이지가 바로 보여집니다.handleError에서 올바르게 리다이렉트가 되도록 합니다.이전에는
tanstack-router의redirect의 쓰임을 제대로 파악하지 못해, 리다이렉트가 적용되지 않았습니다. (beforeLoad나loader에서만 쓰임) 컴포넌트 외부에서 라우팅을 시키기 위해window.location.href를 사용했는데 더 좋은 방법이 있다면 알려주세요!🙏 여기는 꼭 봐주세요! > 리뷰어가 특별히 봐주었으면 하는 부분이 있다면 작성해주세요
Summary by CodeRabbit
Summary by CodeRabbit