[Study/Web] catch문 / finally문

SoShy·2024년 2월 1일

웹 개발

목록 보기
19/21
post-thumbnail

catch문 / finally


아래 코드를 실행해보면, fetch 함수의 인자(argument)가 존재하지 않는 URL이기 때문에, fetch 함수가 리턴하는 promise 객체가 rejected 상태가 되어, 결과적으로 에러가 발생하게 된다.

async function fetchAndPrint () {
  const response = await fetch('https://jsonplaceholder.typicode.comm/users');
  const result = await response.text();
  console.log(result);
}

fetchAndPrint();


이를 해결하려면 어떻게 해야할까?

async / await 구문의 경우, 아래와 같이, try...catch 문을 사용하면 해결이 가능하다.

async function fetchAndPrint () {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.comm/users');
    const result = await response.text();
    console.log(result);
  } catch (error) {
    console.log(error);
  }
}

fetchAndPrint();


여기서 작업의 성공 여부와 관계 없이 동작을 추가하고 싶다면, 아래와 같이, finally 문도 같이 활용이 가능하다.

async function fetchAndPrint () {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.comm/users');
    const result = await response.text();
    console.log(result);
  } catch (error) {
    console.log(error);
  } finally {
    console.log('exit');
  }
}

fetchAndPrint();

profile
안녕하세요. 프론트엔드 개발자 SoShy 입니다.

0개의 댓글