Skip to content

Commit

Permalink
feat: 불필요하게 낭비되는 상태인 hasError를 제거하고 errorMessage는 클라이언트에서 보여지는 에러메세지이…
Browse files Browse the repository at this point in the history
…므로 clientErrorMessage로 이름 수정
  • Loading branch information
pakxe committed Aug 16, 2024
1 parent a3438d0 commit dafaa91
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions client/src/hooks/useError/ErrorProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import {createContext, useState, useEffect, ReactNode} from 'react';

import {SERVER_ERROR_MESSAGES} from '@constants/errorMessage';

// 에러 컨텍스트 생성
export interface ErrorContextType {
clientErrorMessage: string;
setErrorInfo: (error: ErrorInfo) => void;
clearError: (ms?: number) => void;
errorInfo: ErrorInfo | null;
}

export const ErrorContext = createContext<ErrorContextType | undefined>(undefined);

// 에러 컨텍스트를 제공하는 프로바이더 컴포넌트
interface ErrorProviderProps {
children: ReactNode;
callback?: (message: string) => void;
}

export type ErrorInfo = {
errorCode: string;
message: string;
};

export const ErrorProvider = ({children, callback}: ErrorProviderProps) => {
const [clientErrorMessage, setClientErrorMessage] = useState('');
const [errorInfo, setErrorState] = useState<ErrorInfo | null>(null);

useEffect(() => {
if (errorInfo) {
if (isUnhandledError(errorInfo.errorCode)) {
// 에러바운더리로 보내기

throw errorInfo;
}

const message = SERVER_ERROR_MESSAGES[errorInfo.errorCode];
setClientErrorMessage(message);
// callback(message);
}
}, [errorInfo, callback]);

const setErrorInfo = (error: ErrorInfo) => {
setClientErrorMessage('');
setErrorState(error);
};

const clearError = (ms: number = 0) => {
if (errorInfo === null) return;

setTimeout(() => {
setClientErrorMessage('');
setErrorState(null);
}, ms);
};

return (
<ErrorContext.Provider value={{errorInfo, clientErrorMessage, setErrorInfo, clearError}}>
{children}
</ErrorContext.Provider>
);
};

const isUnhandledError = (errorCode: string) => {
if (errorCode === 'INTERNAL_SERVER_ERROR') return true;

return SERVER_ERROR_MESSAGES[errorCode] === undefined;
};

0 comments on commit dafaa91

Please sign in to comment.