JavaScript/Web Development
[JavaScript] async/ await 의 catch/ finally 문
passionfruit
2023. 3. 9. 19:53
다음과 같이 잘못된 url 주소를 입력한 코드를 실행하면,
async function fetchAndPrint() {
const response = await fetch('https://jsonplaceholder.typicode.commm/users');
const result = await response.text();
console.log(result);
}
fetchAndPrint();
다음과 같이 에러가 발생.
[try catch 문]
이 문제를 해결하기 위해 try catch 문을 사용하면,
async function fetchAndPrint() {
try {
const response = await fetch('https://jsonplaceholder.typicode.commm/users');
const result = await response.text();
console.log(result);
} catch (error) {
console.log(error);
}
}
fetchAndPrint();
try 블록 안의 await 이 붙어있는 promise 객체 중, rejected 가 발생하면 코드의 흐름이 catch 문으로 넘어오게 됨. 또한 작업 실패 정보가 담긴 에러 객체 생성.
[finally 문]
async function fetchAndPrint() {
try {
const response = await fetch('https://jsonplaceholder.typicode.commm/users');
const result = await response.text();
console.log(result);
} catch (error) {
console.log(error);
} finally {
console.log('exit');
}
}
fetchAndPrint();
finally 문에 있는 코드는 항상 출력 됨.