Joan’s donation report takes its title from a small settings file, settings.json, which holds {"report": {"title": "October donations"}}. Last week someone edited it by hand and left a comma after the title. That’s valid in a Python dictionary, but it isn’t valid JSON, so the import can’t read the settings at all.
Her Python script catches that with try and except. In this lesson, you’ll port the catch to JavaScript, read the error’s message, and see what becomes of Python’s else and finally.
Catch a Broken Settings File
In Python, json.loads() raises json.JSONDecodeError when the text isn’t valid JSON. The script catches that one exception, prints its message to standard error, and uses the settings only if nothing went wrong:
import json
import sys
text = '{"report": {"title": "October donations",}}'
try:
settings = json.loads(text)
except json.JSONDecodeError as err:
print(f"settings.json is not valid JSON: {err}", file=sys.stderr)
else:
print(settings["report"]["title"])
To keep the example short, text holds the file’s broken contents directly. Python reports Illegal trailing comma before end of object: line 1 column 41 (char 40).
In JavaScript, JSON.parse() turns the text into a value, here an object, and it throws an error when the text is broken. Throw is JavaScript’s word for raise. A line-by-line port wraps the call in try and catch, and with no else yet, the title goes inside the try:
const text = '{"report": {"title": "October donations",}}';
try {
const settings = JSON.parse(text);
console.log(settings.report.title);
} catch (err) {
console.error(`settings.json is not valid JSON: ${err.message}`);
}