In Follow an Error Into catch, Sam’s recipe box learned to survive a damaged save. loadRecipes() wrapped JSON.parse() in try, and when the parse threw, catch handed back the starter recipes instead of leaving the page empty. However, that catch doesn’t ask what went wrong. It catches every error, including ones a fallback can’t fix.
In this lesson, you’ll see what a catch-all hides, and you’ll rewrite the load so that catch handles only a damaged save and lets every other error through. You’ll also find out which problems never reach catch at all. Start with the question the video left open: What else could land in that catch?
See What a Catch-All Hides
The catch block from the video runs the same fallback whatever the error is. That’s a reasonable first version, and it does protect Sam from a damaged save. To see what it costs, debug a case where it goes wrong. Here’s loadRecipes() from the video without the labeled logs and the finally block, after an edit that left a slip somewhere inside it:
function loadRecipes() {
const savedText = localStorage.getItem("recipe-box");
try {
const saved = JSON.prase(savedText);
return saved ?? starterRecipes;
} catch (error) {
console.log(`caught a ${error.name}`);
return starterRecipes;
}
}
const recipes = loadRecipes();
First, check that the page lists Sam’s six recipes, with Pea and mint soup last. If it shows five, add Pea and mint soup again with 4 servings, 25 minutes, Soup selected, and Vegetarian checked.
Then open recipes/main.js, and replace the whole loadRecipes() function from the video, its const recipes = loadRecipes(); call, and the recipes loaded log after it with the code above. If your file still has the two loading lines from Load Saved Data on Every Visit, the savedText and recipes lines, replace those instead. Keep starterRecipes above the replacement code and setUpRecipeBox(document, recipes); at the bottom.
Save, and the page reloads with the five starter recipes, although nothing touched the save. Two clues tell you why. In the Application panel, select the recipe-box row: the preview under the table still shows the save as Array(6), with Pea and mint soup last, so the save isn’t damaged. And the Console shows one quiet line:
caught a TypeError
A damaged save would log caught a SyntaxError, so this catch caught a different error and answered it with the damaged-save fallback. Before you read on, find the line in the try block that could throw a TypeError. It’s JSON.prase: no such function exists, so calling it throws a TypeError. To Sam, the page looks exactly like it did after a damaged save.
The real damage would come with Sam’s next change. Adding a recipe, say Shakshuka, would make saveRecipes() write the page’s recipes over the save: the five starters plus Shakshuka. Pea and mint soup would be gone, with nothing on the page to show it was ever there. Slips happen to everyone. The catch-all could turn a slip you’d fix in seconds into lost data.