KHUCapston-concoder / Frontend

경희대학교 2022-2 캡스톤디자인1 Front 팀입니다.
1 stars 0 forks source link

[Feat] useHttp 훅 내에 error, loading 기능 잘되게 변경 및 에러 핸들링 공통 컴포넌트 개발 #8

Open wjdwl002 opened 1 year ago

wjdwl002 commented 1 year ago

https://github.com/KHUCapston-concoder/Frontend/blob/b0dd564660588eceed258c1cbe22582432056bc0/src/hooks/useHttp.ts#L31-L58

원래 의도는 error, loading 정보를 hook에 담아 모든 httpRequest에 대해 공통으로 처리하려고 하였으나, 모종의 이유로(...) 제대로 동작하지 않는것처럼 보임. 해당 기능을 fix 하고 추가로 error 상황에 대해 공통 컴포넌트로 관리하도록 개선하면 좋을 듯함

https://fe-developers.kakaoent.com/2022/221110-error-boundary/

카카오에서 React16 Error Boundary 기능을 사용해서 에러 핸들링을 한다고 하는데, 참고해서 비슷한 형식으로 개발하면 좋을 듯 합니다.

dhdbstjr98 commented 1 year ago

지나가다 보고 도움이 될까 싶어서 코멘트 드립니다.

본문 코드의 45~51번 라인 try...catch에서 예외처리가 되지 않는 상황으로 이해했습니다.

타입을 보면 requestFunc는 비동기 함수로 보이는데요. 비동기 함수는 await를 사용해야 try~catch에서 Promise reject 상황을 처리할 수 있고 (1), await 없이 사용한다면 Promise의 catch를 직접 사용해야 (2) 합니다.

example

const request = () => Promise.reject('rejected')

// await 없이 Promise.then을 직접 사용한 경우 catch되지 않음
try {
    const response = request().then(console.log)
} catch {
    console.log('catched')
}

// await 를 사용한 경우 catch됨
try {
    const response = await request()
    console.log(response)
} catch {
    console.log('catched')
}

// Promise.catch를 직접 사용
const response = request()
  .then(console.log)
  .catch(() => {
    console.log('catched')
  })

본문의 예시에서는 아래와 같이 고칠 수 있을 것 같습니다.

(1)

   const sendRequest = useCallback( 
     async (data) => { 
       setIsLoading(true); 
       setError(null); 
       const url = "http://163.180.146.59" + requestConfig.url; 

       try { 
         const res = await requestFunc(url, data);
         handleResponse(res.data); 
       } catch (e: any) { 
         setError(e.message); 
       } 
       setIsLoading(false); 
     }, 
     [isLoading, error, requestConfig] 
   ); 

(2)

   const sendRequest = useCallback( 
     async (data) => { 
       setIsLoading(true); 
       setError(null); 
       const url = "http://163.180.146.59" + requestConfig.url; 

       requestFunc(url, data)
         .then((res: any) => { 
           handleResponse(res.data); 
           setIsLoading(false); // 의미상 then 하위로 이동하는게 맞을 것 같습니다
         }).catch((e: any) => {
           setError(e.message); 
         }); 
     }, 
     [isLoading, error, requestConfig] 
   ); 
wjdwl002 commented 1 year ago

@dhdbstjr98 감사합니다 ... 급하게 짠 구멍숭숭 코드인데 약간 부끄럽네요 ... 많은 도움이 됐습니다 !!!!!! 조언 참고해서 fix 해보겠습니다 :)