참고: 이웅모 《모던 자바스크립트 Deep Dive》 47장 · 본인 말로 정리 (원문 긴 인용·캡처 없음)
보강: MDN Error, try...catch
에러 나면 console.log만 하고 넘어간 적 많다.
try/catch는 감싸면 안 터지겠지 수준이었다.
Deep Dive 47장을 읽고 에러도 제어 흐름이라는 말이 남았다.
Deep Dive 47.1절.
예외를 무시하면 앱이 이상한 상태로 계속 돈다.
비유: 연기가 나는데 창문만 닫고 요리하기.
Deep Dive 47.2절.
function readConfig(json) {
try {
return JSON.parse(json)
} catch (err) {
console.error('config broken', err)
return { theme: 'light' }
} finally {
console.log('parse attempt finished')
}
}
이게 무슨 말이냐.
try = 위험 구간, catch = 복구/기록, finally = 성공/실패와 무관 정리.
Deep Dive 47.3~47.5절.
new Error(message)가 스택이 있어 디버깅에 유리하다.
동기 throw는 호출자로 올라가고, async 안 throw는 프로미스 reject로 바뀐다.
async function load() {
try {
const res = await fetch('/api')
if (!res.ok) throw new Error('bad status')
return await res.json()
} catch (e) {
console.error(e)
throw e
}
}