JavaScript fetch 함수에서 Error 핸들링하기

JS에서는 에러 핸들링을 어떻게 할까?

fetch(`/users/${id}`, {
    method: "DELETE",
    headers: {
        "Content-Type": "application/json",
    },
})
    .then((res) => {
        if (!res.ok) {
            return res.json().then(body => {
                throw new Error(`HTTP Error! status : ${body.status}, message : ${body.message}`);
            })
        }
        return res.json();
    })
    .then((data) => {
        alert("결과 : " + data.message);
        location.reload();
    })
    .catch(error => {
        alert(error.message);
    });

js에서는, 직접 Error 클래스를 만들기보다, Error클래스를 반환하는 식으로 사용한다. catch에서 클래스별로 에러를 잡을 수 있는 게 아니기 때문이다. 그렇다면, 코드에 따라 에러를 잡고 싶다면 방법이 없는걸까?

해결 방법

js는 객체에 아주 쉽게 프로퍼티를 추가할 수 있다. 때문에, 단순히 바로 status라는 프로퍼티를 추가해서 잡아주었다. 403 status 코드를 내려준 경우, access-denied 페이지로 이동시켜주었다.

fetch(`/users/${id}`, {
  method: "DELETE",
  headers: {
    "Content-Type": "application/json",
  },
})
  .then((res) => {
    if (!res.ok) { sv
      return res.json().then(body => {
        const error = new Error(`HTTP Error! status : ${body.status}, message : ${body.message}`);
        error.status = res.status;
        throw error;
      })
    }
    return res.json();
  })
  .then((data) => {
    alert("결과 : " + data.message);
    location.reload();
  })
  .catch(error => {
    alert(error.message);
    if (error.status == 403) {
      location.href = "/access-denied";
    }
  });

댓글

개발자  김철준

백엔드 개발자 김철준의 블로그입니다.

주요 프로젝트