Skip to content
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

[FE] HTTP 요청 오류 시 status code별 오류 상황을 대응하는 함수 생성 #151

Merged
merged 4 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
11 changes: 11 additions & 0 deletions frontend/src/apis/apiErrorMessageCreator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { API_ERROR_MESSAGE, SERVER_ERROR_REGEX } from '@/constants';

const createApiErrorMessage = (statusCode: number) => {
const isServerError = SERVER_ERROR_REGEX.test(statusCode.toString());
Copy link
Contributor

Choose a reason for hiding this comment

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

서버 에러인지를 판별할 때 특별히 정규 표현식을 사용한 이유가 있을까요?
그리고 코드 보고 갑자기 생각난 건데 문자열로 변환이 필요할 때 toStringString중 무엇을 사용할지 팀원들과 간단하게 논의해보면 좋겠어요~

Copy link
Contributor Author

Choose a reason for hiding this comment

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

500대의 에러를 잡기 위해서 정규표현식을 사용했어요.

Copy link
Contributor

Choose a reason for hiding this comment

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

아래 코드처럼 서버 에러를 확인하는 방법은 여러가지가 있었을 거라 생각하는데, 정규표현식을 사용한 이유가 있을까요?

const isServerError = statusCode >= 500 && statusCode < 600; 

Copy link
Contributor Author

Choose a reason for hiding this comment

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

500, 600이라는 매직넘버가 생기고 매직넘버를 피하기 위해서 상수처리는 해야해요.
정규표현식을 사용하면 하나의 상수만 만들면 되고, 어렵지 않은 정규표현식이라 가독성면에서도 500대 에러라는 것을 비교연산자만큼 아니면 그보다 더 쉽게 파악할 수 있을거라 생각했어요.


if (isServerError) return API_ERROR_MESSAGE.serverError;

if (statusCode in API_ERROR_MESSAGE) return API_ERROR_MESSAGE[statusCode];
};

export default createApiErrorMessage;
10 changes: 5 additions & 5 deletions frontend/src/apis/review.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//리뷰 작성
import { ReviewData, WritingReviewInfoData } from '@/types';

import createApiErrorMessage from './apiErrorMessageCreator';
import endPoint from './endpoints';

export const getDataToWriteReviewApi = async (reviewerGroupId: number) => {
Expand All @@ -9,7 +9,7 @@ export const getDataToWriteReviewApi = async (reviewerGroupId: number) => {
});

if (!response.ok) {
throw new Error('리뷰 쓰기 위한 정보를 가져오는데 실패했습니다.');
throw new Error(createApiErrorMessage(response.status));
}

const data = await response.json();
Expand All @@ -26,7 +26,7 @@ export const postReviewApi = async ({ reviewData }: { reviewData: ReviewData })
});

if (!response.ok) {
throw new Error('리뷰를 작성하는 데 실패했습니다.');
throw new Error(createApiErrorMessage(response.status));
}

const data = await response.json();
Expand All @@ -43,7 +43,7 @@ export const getDetailedReviewApi = async ({ reviewId, memberId }: { reviewId: n
});

if (!response.ok) {
throw new Error('상세 리뷰를 불러오는 데 실패했습니다.');
throw new Error(createApiErrorMessage(response.status));
}

const data = await response.json();
Expand All @@ -68,7 +68,7 @@ export const getReviewListApi = async ({
});

if (!response.ok) {
throw new Error('리뷰 리스트를 불러오는 데 실패했습니다.');
throw new Error(createApiErrorMessage(response.status));
}

const data = await response.json();
Expand Down
15 changes: 15 additions & 0 deletions frontend/src/constants/apiErrorMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
interface ApiErrorMessages {
[key: number]: string;
serverError: string;
}

export const API_ERROR_MESSAGE: ApiErrorMessages = {
400: '유효하지 않은 요청 형식이에요.',
401: '인증을 실패했어요.',
403: '요청권한이 없어요.',
404: '요청한 페이지를 찾을 수 없어요.',
422: '요청이 잘못되었거나 비즈니스 로직을 위반했어요.',
Copy link
Contributor

Choose a reason for hiding this comment

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

422 에러는 요청이 제대로 갔지만 처리되지 않는 오류로 알고 있어요! https://developer.mozilla.org/ko/docs/Web/HTTP/Status/422

오류 메시지를 다시 고민해보면 어떨까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

'올바르지 않은 데이터 형식이에요.', 로 수정했어요.

클라이언트의 json이 잘못된 경우인 400과 보낸 요청의 유효성 검사가 실패한 422의 에러 메세지가 구별이 될 수 있도록
400의 에러 메세지는'잘못된 요청에요.'로 수정했어요.
수정된 메세지들도 확인부탁드려요

serverError: '서버 오류가 발생했어요.',
};

export const SERVER_ERROR_REGEX = /^5\d{2}$/;
2 changes: 2 additions & 0 deletions frontend/src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export * from './page';
export * from './apiErrorMessage';
export * from './review';