Handling Errors
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 13 of 24.
A notes.json edited by hand can break, and then JSON.parse throws and Node prints a stack trace.
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
Easy- When
notes.jsonis not valid JSON, every command printsnotes.json is damaged: <message>to stderr and exits with1. - The starter's
notes.jsonis damaged on purpose.
Run node notes.js list before and after your change. Then delete the extra comma in notes.json and run list again.
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, NodeCommand-Line ArgumentsCommandsPractice on your own: Express playground