오류 처리
Coddy Node.js 여정의 Node.js 기초 섹션에 포함된 레슨. 24개 중 13번째.
수동으로 편집한 notes.json 파일은 손상될 수 있으며, 그러면 JSON.parse에서 예외가 발생하고 Node가 스택 추적을 출력합니다.
try는 예외가 발생할 수 있는 코드를 실행합니다. 예외가 발생하면 catch가 오류를 받아 프로그램에서 무엇을 알릴지 결정합니다. err.message는 한 줄로 표시되는 원인입니다.
let config;
try {
config = JSON.parse('{ port: 3000 }');
} catch (err) {
console.error(`config is broken: ${err.message}`);
process.exit(1);
}오류를 잡은 뒤 빈 목록으로 계속 진행하지 마세요. 다음 add를 실행하면 손상된 파일을 덮어쓰게 되고, 파일에 있던 모든 메모가 사라집니다.
챌린지
쉬움notes.json이 유효한 JSON이 아니면 모든 명령은 표준 오류에notes.json is damaged: <message>를 출력하고1로 종료합니다.- 시작 파일의
notes.json은 의도적으로 손상되어 있습니다.
변경하기 전과 후에 node notes.js list를 실행하세요. 그런 다음 notes.json에서 쉼표를 하나 더 삭제하고 list를 다시 실행하세요.
직접 해보기
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
const file = 'notes.json';
const store = {
notes: existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : [],
save() {
writeFileSync(file, JSON.stringify(this.notes, null, 2));
},
add(text) {
this.notes.push(text);
this.save();
return this.notes.length;
},
remove(n) {
const [text] = this.notes.splice(n - 1, 1);
this.save();
return text;
},
};
export default store;