Menu
CoddyTech

エラー処理

CoddyのNode.jsジャーニー「Node.jsの基礎」セクションの一部。レッスン 13/24。

手作業で編集したnotes.jsonは壊れることがあり、その場合JSON.parseが例外をスローし、Nodeはスタックトレースを表示します。

tryは、例外をスローする可能性のあるコードを実行します。例外が発生すると、catchがエラーを受け取り、プログラムが何を伝えるかを決めます。err.messageは、理由を1行で示します。

let config;
try {
    config = JSON.parse('{ port: 3000 }');
} catch (err) {
    console.error(`config is broken: ${err.message}`);
    process.exit(1);
}

エラーを捕捉して、空のリストで処理を続けてはいけません。次のaddで破損したファイルが上書き保存され、そこにあったすべてのメモが失われます。

challenge icon

チャレンジ

簡単
  • 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;

Node.jsの基礎のすべてのレッスン