diff --git a/client/src/ErrorProvider.tsx b/client/src/ErrorProvider.tsx deleted file mode 100644 index c657d9337..000000000 --- a/client/src/ErrorProvider.tsx +++ /dev/null @@ -1,83 +0,0 @@ -import {createContext, useState, useContext, useEffect, ReactNode} from 'react'; - -import {SERVER_ERROR_MESSAGES} from '@constants/errorMessage'; - -// 에러 컨텍스트 생성 -interface ErrorContextType { - hasError: boolean; - errorMessage: string; - setError: (error: ServerError) => void; - clearError: (ms?: number) => void; - error: ServerError | null; -} - -const ErrorContext = createContext(undefined); - -// 에러 컨텍스트를 제공하는 프로바이더 컴포넌트 -interface ErrorProviderProps { - children: ReactNode; - callback?: (message: string) => void; -} - -export type ServerError = { - errorCode: string; - message: string; -}; - -export const ErrorProvider = ({children, callback}: ErrorProviderProps) => { - const [hasError, setHasError] = useState(false); - const [errorMessage, setErrorMessage] = useState(''); - const [error, setErrorState] = useState(null); - - useEffect(() => { - if (error) { - if (isUnhandledError(error.errorCode)) { - // 에러바운더리로 보내기 - - throw error; - } - - setHasError(true); - const message = SERVER_ERROR_MESSAGES[error.errorCode]; - setErrorMessage(message); - // callback(message); - } - }, [error, callback]); - - const setError = (error: ServerError) => { - setHasError(true); - setErrorMessage(''); - setErrorState(error); - }; - - const clearError = (ms: number = 0) => { - if (error === null) return; - - setTimeout(() => { - setHasError(false); - setErrorMessage(''); - setErrorState(null); - }, ms); - }; - - return ( - - {children} - - ); -}; - -// 에러 컨텍스트를 사용하는 커스텀 훅 -export const useError = (): ErrorContextType => { - const context = useContext(ErrorContext); - if (!context) { - throw new Error('useError must be used within an ErrorProvider'); - } - return context; -}; - -const isUnhandledError = (errorCode: string) => { - if (errorCode === 'INTERNAL_SERVER_ERROR') return true; - - return SERVER_ERROR_MESSAGES[errorCode] === undefined; -}; diff --git a/client/src/hooks/useError/useError.tsx b/client/src/hooks/useError/useError.tsx new file mode 100644 index 000000000..ee7176233 --- /dev/null +++ b/client/src/hooks/useError/useError.tsx @@ -0,0 +1,12 @@ +import {useContext} from 'react'; + +import {ErrorContext, ErrorContextType} from './ErrorProvider'; + +// 에러 컨텍스트를 사용하는 커스텀 훅 +export const useError = (): ErrorContextType => { + const context = useContext(ErrorContext); + if (!context) { + throw new Error('useError must be used within an ErrorProvider'); + } + return context; +};