
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();
