JavaScriptLesson 14 of 16
JSON and error handling
JSON is the text format programs use to store and send data. try...catch makes sure one broken record does not bring the whole program down.
Key points
- JSON.stringify(obj) turns an object into a string, JSON.parse(text) turns it back
- In JSON, keys and strings use double quotes only, and there are no functions or undefined
- try { … } catch (error) { … } finally { … }: catch handles the error, finally always runs
- throw new Error("…") raises your own error, with a name and a message
- The text of a SyntaxError differs between browsers, so check error.name instead
Example
const user = { name: "Ola", langs: ["js", "css"], active: true }; const text = JSON.stringify(user);console.log(text); const copy = JSON.parse(text);console.log(copy.langs[1], copy === user); try { JSON.parse("{oops}"); console.log("This line never runs");} catch (error) { console.log("Caught:", error.name);} finally { console.log("Done");}JSON.parse built a brand-new copy, so copy === user is false. {oops} is not JSON: parse threw a SyntaxError, catch caught it and finally ran anyway.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.One game save is broken and another has no score. Finish readPlayer(text): parse the JSON inside try, throw new Error("Missing score") when score is missing, and in catch print Skipped: broken JSON for a SyntaxError or Skipped: plus the error message otherwise, then return null. Output: Skipped: broken JSON, Skipped: Missing score, Loaded: 2 and the JSON of the two players.
Output
What your program prints appears here.