์๋ฌ ์ฒ๋ฆฌ
- ์๋ฌ๋ ํธ์ถ์(caller) ๋ฐฉํฅ์ผ๋ก ์ ํ
- ์ฝ ์คํ์ ์๋ ๋ฐฉํฅ(์คํ ์ค์ธ ์คํ ์ปจํ
์คํธ๊ฐ ํธ์๋๊ธฐ ์ง์ ์ ํธ์๋ ์คํ ์ปจํ
์คํธ ๋ฐฉํฅ)์ผ๋ก ์ ํ
- ํ์ง๋ง, ๋น๋๊ธฐ ํจ์์ ์ฝ๋ฐฑ ํจ์๋ฅผ ํธ์ถํ ๊ฒ์ ๋น๋๊ธฐ ํจ์๊ฐ ์๋๊ธฐ ๋๋ฌธ์ try…catch๋ฌธ์ ์ฌ์ฉํด ์๋ฌ๋ฅผ ์บ์นํ ์ ์์
try{
setTimeout(()=>{ throw new Error('Error!') },1000)
} catch(e) [
cosole.log('์บ์นํ ์๋ฌ',e)
}
- async/await์์๋ ์๋ฌ ์ฒ๋ฆฌ์ try...catch ๋ฌธ์ ์ฌ์ฉํ ์ ์์.
- ์ฝ๋ฐฑ ํจ์๋ฅผ ์ธ์๋ก ์ ๋ฌ๋ฐ๋ ๋น๋๊ธฐ ํจ์์๋ ๋ฌ๋ฆฌ ํ๋ก๋ฏธ์ค๋ฅผ ๋ฐํํ๋ ๋น๋๊ธฐ ํจ์๋ ๋ช
์์ ์ผ๋ก ํธ์ถ ํ ์ ์๊ธฐ ๋๋ฌธ์ ํธ์ถ์๊ฐ ๋ช
ํ.
const fetch = require('node-fetch')
const foo = async()=>{
try{
const wrongUrl = '<https://wrong.url>'
const response = await(fetch(wrongUrl)
const data = await respone.json()
console.log(data)
} catch(err) {
console.log(err) //Type Error : Failed to fetch
}
}
foo()
- fooํจ์์ catch๋ฌธ์ HTTPํต์ ์์ ๋ฐใน์ํ ๋คํธ์ํฌ ์๋ฌ๋ฟ ์๋๋ผ try ์ฝ๋ ๋ธ๋ก ๋ด์ ๋ชจ๋ ๋ฌธ์์ ๋ฐ์ํ ์ผ๋ฐ์ ์ธ ์๋ฌ๊น์ง ๋ชจ๋ ์บ์น ๊ฐ๋ฅ
- async ํจ์ ๋ด์์ catch ๋ฌธ์ ์ฌ์ฉํด์ ์๋ฌ ์ฒ๋ฆฌ๋ฅผ ํ์ง ์์ผ๋ฉด async ํจ์๋ ๋ฐ์ํ ์๋ฌ๋ฅผ rejet ํ๋ ํ๋ก๋ฏธ์ค๋ฅผ ๋ฐํ
const fetch = require('node-fetch')
const foo = async()=>{
try{
const wrongUrl = '<https://wrong.url>'
const response = await(fetch(wrongUrl)
const data = await respone.json()
return data
}
foo()
.then(console.log)
.cach(console.error) //TypeError:Failed to fetch
- async ํจ์๋ฅผ ํธ์ถํ๊ณ Promise.prototype.catch ํ์ ์ฒ๋ฆฌ ๋ฉ์๋๋ฅผ ์ฌ์ฉํด ์๋ฌ๋ฅผ ์บ์น
Reference
- ์ด์
๋ชจ ์ , ใ๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ Deep Diveใ, ์ํค๋ถ์ค(2020)
๋๊ธ