Handling Errors
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 16 of 33.
A notes.json edited by hand can break. Then JSON.parse throws, and Node prints a stack trace: the long list of code lines that led to the error.
try runs code that may throw. When it does, catch receives the error and your program decides what to say. err.message is the one-line reason.
let config;
try {
config = JSON.parse('{ port: 3000 }');
} catch (err) {
console.error(`config is broken: ${err.message}`);
process.exit(1);
}Do not catch the error and carry on with an empty list: the next add would save over the damaged file, and every note in it would be gone.
Challenge
EasySomeone edited notes.json by hand and left one comma too many. Now JSON.parse throws, and Node prints a long stack trace. Make the tool print one clear line instead and stop, so it never saves over the damaged file.
- In
store.js, find where the notes are loaded:JSON.parse(readFileSync(...)), inside thestoreobject. Catch the error thatJSON.parsethrows when the file is not valid JSON. Atrycannot go inside an object, so move the loading into a function, or a variable, above the object, and use its result fornotes. - When the parse fails, print one line to stderr, then exit with code 1. The line starts with
notes.json is damaged:and goes on with the error's message, which is the reasonJSON.parsegives, such asUnexpected token ']'. Do not print the stack trace. Do not carry on with an empty list: the nextaddwould save over the damaged notes. - A missing
notes.jsonstill means an empty store, as before. The check runs for every command, because every command loads the store.
Try it: type list in the box after $ node notes.js before you change anything. You see a red stack trace. After your change, list prints only the red line notes.json is damaged: ... and exit code 1. To see your notes again, delete the comma after "Call Ada" in notes.json and run list. Then put the comma back before you press Check: the checks need the damaged file, and Reset files does not undo your own edits.
Try it yourself
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;
All lessons in Node.js Basics
1Running JavaScript on Node
Hello, NodeReading the CommandCommand-Line ArgumentsCommands3Files
JSON Text and ValuesReading a FileWriting JSON TextWriting a FileRemoving a NotePractice on your own: Express playground