Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions apps/web/src/features/auth/model/useWithdraw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { useToast } from '@/shared/ui';
import { clearAllUserStorage } from '@/shared/utils';
import { authQueries } from './authQueries';
import { useBridge } from '@/shared/lib/bridge';
import { handleApiError } from '@/shared/api';

export const useWithdraw = () => {
const router = useRouter();
Expand All @@ -29,12 +30,13 @@ export const useWithdraw = () => {
toast.success('회원탈퇴가 완료되었어요');
router.replace('/login');
},
onError: (error: Error) => {
const message =
error?.message && error.message !== 'Failed to fetch'
? error.message
: '회원 탈퇴에 실패했어요. 다시 시도해주세요.';
toast.attention(message);
onError: (error) => {
handleApiError(error, {
toast,
fallback: '회원 탈퇴에 실패했어요. 다시 시도해 주세요.',
context: 'auth.withdraw',
preferServerMessage: true,
});
},
});

Expand Down
15 changes: 11 additions & 4 deletions apps/web/src/features/expense/ui/ExpenseEditBottomSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
} from '@/entities/expense';
import { expenseReportQueries } from '@/entities/expenseReport';
import { expenseEditNavigation } from '@/features/expense/lib/expenseEditNavigation';
import { handleApiError } from '@/shared/api';

export interface ExpenseEditBottomSheetProps {
isOpen: boolean;
Expand Down Expand Up @@ -88,8 +89,11 @@ export const ExpenseEditBottomSheet = ({
onClose();
},
onError: (error) => {
console.error('지출 수정 실패:', error);
toast.attention('수정에 실패했어요. 다시 시도해 주세요.');
handleApiError(error, {
toast,
fallback: '수정에 실패했어요. 다시 시도해 주세요.',
context: 'expense.update',
});
},
});
// 지출 삭제 mutation
Expand All @@ -105,8 +109,11 @@ export const ExpenseEditBottomSheet = ({
onClose();
},
onError: (error) => {
console.error('지출 삭제 실패:', error);
toast.attention('삭제에 실패했어요. 다시 시도해 주세요.');
handleApiError(error, {
toast,
fallback: '삭제에 실패했어요. 다시 시도해 주세요.',
context: 'expense.delete',
});
},
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { useExpenseFormStore } from '@/widgets/expenseRecordFunnel/model/store';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { categoryQueries } from '@/features/expense/model/categoryQueries';
import { CategoryDetailsDTO } from '@/features/expense/model/types';
import { handleApiError } from '@/shared/api';

const VALID_NAME_REGEX = /^[가-힣ㄱ-ㅎㅏ-ㅣa-zA-Z0-9]*$/;

Expand Down Expand Up @@ -60,6 +61,13 @@ export const AddCategoryStep = ({ onBack }: AddCategoryStepProps) => {
useExpenseFormStore.setState({ shouldOpenCategorySheet: false });
onBack();
},
onError: (error) => {
handleApiError(error, {
toast,
fallback: '카테고리 추가에 실패했어요. 다시 시도해 주세요.',
context: 'category.create',
});
},
});

const [categoryName, setCategoryName] = useState('');
Expand Down
9 changes: 7 additions & 2 deletions apps/web/src/features/inquiry/model/useInquiryForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useModal } from '@/shared/hooks';
import { isValidEmail, hasEmailError } from '@/shared/lib/validation';
import { inquiryQueries } from './inquiryQueries';
import { useToast } from '@/shared/ui';
import { handleApiError } from '@/shared/api';

/**
* 문의 폼 상태 및 동작을 관리하는 커스텀 훅
Expand All @@ -25,8 +26,12 @@ export const useInquiryForm = () => {
toast.success('등록 완료, 곧 답변드릴게요!');
router.back();
},
onError: () => {
toast.attention('문의 등록에 실패했어요. 다시 시도해주세요.');
onError: (error) => {
handleApiError(error, {
toast,
fallback: '문의 등록에 실패했어요. 다시 시도해 주세요.',
context: 'inquiry.send',
});
},
});

Expand Down
8 changes: 8 additions & 0 deletions apps/web/src/features/review/model/useSpendingReview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { ROUTES } from '@/shared/constants/routes';
import { useRetrospectExpenses } from './useRetrospectExpenses';
import { patchRemind } from '../api/patchRemind';
import { useReviewCarousel, type UseReviewCarouselReturn } from './useReviewCarousel';
import { handleApiError } from '@/shared/api';

type UseSpendingReviewReturn = Pick<
UseReviewCarouselReturn,
Expand Down Expand Up @@ -63,6 +64,13 @@ export const useSpendingReview = ({ date }: UseSpendingReviewParams): UseSpendin
toast.success('만족도 기록이 잘 저장되었어요!');
router.push(ROUTES.HOME);
},
onError: (error) => {
handleApiError(error, {
toast,
fallback: '저장에 실패했어요. 다시 시도해 주세요.',
context: 'review.saveRemind',
});
},
});

const buildRemindBody = () =>
Expand Down
8 changes: 5 additions & 3 deletions apps/web/src/shared/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,12 @@ export const apiClient = ky.create({
}
if (error.response) {
try {
const body = await error.response.text();
error.message = `${error.message}: ${body}`;
const body = (await error.response.clone().json()) as { message?: string };
if (body?.message) {
error.message = body.message;
}
} catch {
// 응답 본문 읽기 실패 시 무시
// JSON 파싱 실패 시 원본 message 유지
}
}
return error;
Expand Down
43 changes: 43 additions & 0 deletions apps/web/src/shared/api/handleApiError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { HTTPError } from 'ky';

export interface ToastApi {
attention: (message: string) => void;
}

export interface HandleApiErrorOptions {
/** 사용자에게 노출할 기본 실패 문구 (서버 메시지가 없거나 사용 불가일 때 사용) */
fallback: string;
/** 토스트 인스턴스 (useToast() 결과) */
toast: ToastApi;
/** 디버깅용 컨텍스트 (예: 'expense.update') */
context?: string;
/**
* true이면 HTTP 응답에서 받은 서버 메시지(error.message)를 우선 노출.
* 네트워크 오류 등 응답이 없는 경우엔 fallback을 사용.
* 기본 false.
*/
preferServerMessage?: boolean;
}

const SILENT_STATUS = new Set([401, 403]);

/**
* mutation/쿼리의 onError에서 사용할 공통 핸들러.
* - 401/403은 client.ts에서 reissue/리다이렉트 처리하므로 토스트를 띄우지 않음
* - 기본은 fallback 문구 노출. preferServerMessage=true이면 HTTPError의 서버 메시지 우선
* - console.error를 일관 포맷으로 출력
*/
export const handleApiError = (error: unknown, options: HandleApiErrorOptions) => {
const { fallback, toast, context, preferServerMessage = false } = options;

if (error instanceof HTTPError && SILENT_STATUS.has(error.response.status)) {
return;
}

console.error(`[API Error]${context ? ` ${context}` : ''}:`, error);

const serverMessage =
preferServerMessage && error instanceof HTTPError && error.message ? error.message : null;

toast.attention(serverMessage ?? fallback);
Comment on lines +39 to +42

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

preferServerMessage 사용 시 ky의 기본 에러 메시지가 노출될 위험

client.tsbeforeError는 응답 body를 JSON 파싱해 body.message가 있을 때만 error.message를 덮어씁니다. 따라서 응답이 JSON이 아니거나 message 필드가 없는 경우 error.message는 ky의 기본 문자열(예: Request failed with status code 500)이 그대로 남습니다. 현재 로직은 error.message가 truthy이기만 하면 이를 토스트에 노출하므로, preferServerMessage: trueuseWithdraw 같은 호출에서 사용자에게 영문 ky 메시지가 그대로 보일 수 있습니다.

서버가 실제로 메시지를 내려줬을 때만 이를 우선하도록, 서버 메시지를 별도 필드에 저장해 구분하는 것을 권장합니다.

♻️ 제안: 서버 메시지를 별도 필드로 보관
// apps/web/src/shared/api/client.ts (beforeError)
 if (error.response) {
   try {
     const body = (await error.response.clone().json()) as { message?: string };
     if (body?.message) {
       error.message = body.message;
+      (error as HTTPError & { serverMessage?: string }).serverMessage = body.message;
     }
   } catch {
     // JSON 파싱 실패 시 원본 message 유지
   }
 }
// handleApiError.ts
   const serverMessage =
-    preferServerMessage && error instanceof HTTPError && error.message ? error.message : null;
+    preferServerMessage && error instanceof HTTPError
+      ? ((error as HTTPError & { serverMessage?: string }).serverMessage ?? null)
+      : null;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const serverMessage =
preferServerMessage && error instanceof HTTPError && error.message ? error.message : null;
toast.attention(serverMessage ?? fallback);
const serverMessage =
preferServerMessage && error instanceof HTTPError
? ((error as HTTPError & { serverMessage?: string }).serverMessage ?? null)
: null;
toast.attention(serverMessage ?? fallback);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web/src/shared/api/handleApiError.ts` around lines 39 - 42, The current
logic uses error.message when preferServerMessage is true, which can expose ky's
generic messages; update handleApiError to use a distinct server-specific
property (e.g., error.serverMessage) instead of error.message when
preferServerMessage is requested, and only show that value if it exists; also
modify client.ts's beforeError handler to parse the JSON body and set
error.serverMessage = body.message (or undefined) whenever a server-provided
message exists so you can reliably distinguish server messages from ky's default
messages; finally change the toast call to prefer error.serverMessage (if
preferServerMessage) else fallback.

};
2 changes: 2 additions & 0 deletions apps/web/src/shared/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@ export { apiClient, authenticatedApiClient } from './client';
export { api, authApi } from './methods';
export { API_BASE_URL, API_TIMEOUT, API_RETRY_LIMIT } from './constants';
export { ENDPOINT } from './endpoint';
export { handleApiError } from './handleApiError';
export type { ApiResponse } from './types';
export type { HandleApiErrorOptions, ToastApi } from './handleApiError';
15 changes: 15 additions & 0 deletions apps/web/src/widgets/addCategory/ui/AddCategory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { useExpenseFormStore } from '@/widgets/expenseRecordFunnel/model/store';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { categoryQueries } from '@/features/expense/model/categoryQueries';
import { CategoryDetailsDTO } from '@/features/expense/model/types';
import { handleApiError } from '@/shared/api';

const VALID_NAME_REGEX = /^[가-힣ㄱ-ㅎㅏ-ㅣa-zA-Z0-9]*$/;

Expand Down Expand Up @@ -68,6 +69,13 @@ export const AddCategory = () => {
}
toast.success('카테고리가 추가되었어요!');
},
onError: (error) => {
handleApiError(error, {
toast,
fallback: '카테고리 추가에 실패했어요. 다시 시도해 주세요.',
context: 'category.create',
});
},
});

const { mutate: updateCategory, isPending: isUpdatePending } = useMutation({
Expand All @@ -78,6 +86,13 @@ export const AddCategory = () => {
toast.success('수정한 내용이 저장되었어요!');
router.back();
},
onError: (error) => {
handleApiError(error, {
toast,
fallback: '카테고리 수정에 실패했어요. 다시 시도해 주세요.',
context: 'category.update',
});
},
});

const isPending = isCreatePending || isUpdatePending;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query';
import { expenseReportQueries } from '@/entities/expenseReport';
import { expenseQueries as entityExpenseQueries } from '@/entities/expense';
import { ROUTES } from '@/shared/constants';
import { handleApiError } from '@/shared/api';

const STEP_NUMBER = {
금액날짜입력: 1,
Expand Down Expand Up @@ -86,7 +87,16 @@ export const ExpenseRecordFunnel = () => {
history.push('만족도입력', { usageHistory, categoryId });
};

const { mutate: submitExpense, isPending } = useMutation(expenseQueries.recordMutation());
const { mutate: submitExpense, isPending } = useMutation({
...expenseQueries.recordMutation(),
onError: (error) => {
handleApiError(error, {
toast,
fallback: '저장에 실패했어요. 다시 시도해 주세요.',
context: 'expense.create',
});
},
});

const handleSubmit = (emotionType: EmotionType) => {
if (isPending) return;
Expand All @@ -106,9 +116,6 @@ export const ExpenseRecordFunnel = () => {
toast.success('소비 기록이 저장되었어요.');
router.push(ROUTES.HOME);
},
onError: () => {
toast.attention('저장에 실패했어요. 다시 시도해 주세요.');
},
}
);
};
Expand Down
4 changes: 4 additions & 0 deletions apps/web/src/widgets/notifications/ui/Notifications.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export const Notifications = ({ onBackClick }: NotificationsProps) => {
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: notificationQueries.all });
},
onError: (error) => {
// 읽음 처리는 백그라운드성 동작이라 토스트 없이 로그만 남긴다
console.error('[API Error] notification.readAll:', error);
},
});

const handleBackClick = () => {
Expand Down
Loading