fetch 에러 핸들링

  • fetch 는 api 통신에 사용
  • fetch로 에러 핸들링 하는 템플릿

코드


let handleError = function (err) {
  console.log(err)
  return new Response(JSON.stringify({ // response객체를 새로 만들때
      code: 400,
      message: 'Stupid network Error'
  }));
  //그냥 새로운 json을 return 하는 방식도 좋다.
  // return {"code":400,"message":"stupid network error"}
};

let response = await fetch(url,headers)
    .then((res)=>{
      //state에 따른 헨들링 부분
      if(res.status===200){
        return res.json()
      }else{
        throw `error status ${res.status}` // catch로 넘어간다.
      }
    })
    .catch(handleError)//throw로 받는 부분

참고

  • https://stackoverflow.com/questions/61834626/fetch-api-get-request-with-status-200-returning-an-empty-body
  • https://stackoverflow.com/questions/54163952/async-await-in-fetch-how-to-handle-errors
  • https://stackoverflow.com/questions/36840396/fetch-gives-an-empty-response-body